正则表达式与哈希循环全解析
按预定顺序遍历哈希表
在编程中,有时我们希望按照键插入哈希表的顺序来遍历它们。要实现这一点,需要维护一个单独的数组来存储这些键。每次向哈希表中添加一个键时,也需要将该键添加到数组中。示例代码如下:
my @keys_in_order; my %hash; $hash{'thing'} = 1; push @keys_in_order, 'thing'; $hash{$key} = $val; push @keys_in_order, $key;不过,这种策略存在一些问题。如果某个键被重新赋值或删除,数组可能会与哈希表不同步。
使用 while 和 each 遍历哈希表
通常,使用foreach循环遍历哈希表是标准做法,但有时使用each()函数结合while循环会更简洁。以下是两种执行相同操作的循环对比:
while (my ($key, $value) = each %hash_with_long_name) { print "$key, $value\n"; } foreach my $key (keys %hash_with_long_name) { print "$key, $hash_with_long_name{$key}\n"; }