Perl 如果我们在each循环中更改/更新散列值会发生什么?
“perldoc-f each”表示在迭代时删除或添加一个值是不安全的,除非该项是each()最近返回的 当我运行此代码snnipet时:Perl 如果我们在each循环中更改/更新散列值会发生什么?,perl,function,hash,each,tie,Perl,Function,Hash,Each,Tie,“perldoc-f each”表示在迭代时删除或添加一个值是不安全的,除非该项是each()最近返回的 当我运行此代码snnipet时: my ($key,$value); my %fruits = qw/ banana 1 apple 2 grape 3 /; while ( $key = each %fruits ) { $fruits{$key} *= 7; print "$key = $fruits{$key}\n"; } print "\nRead only\n
my ($key,$value);
my %fruits = qw/ banana 1 apple 2 grape 3 /;
while ( $key = each %fruits ) {
$fruits{$key} *= 7;
print "$key = $fruits{$key}\n";
}
print "\nRead only\n\n";
while ( ($key,$value) = each %fruits ) {
print "$key = $value\n";
}
一切都很好
但如果我使用绑定哈希,humnn:
#-------------------------------------------------------------------------------
# select entries on database to print or to update.
sub select_urls {
my ($dbPath,$match,$newValue) = @_;
tie(my %tiedHash,'DB_File',$dbPath,O_RDWR|O_EXLOCK,0600,$DB_BTREE) || die("$program_name: $dbPath: $!\n");
while ( my($key,$value) = each %tiedHash ) {
if ( $key =~ $match ){
if ( defined $newValue ) {
$tiedHash{$key} = $newValue;
($key,$value) = each %tiedHash; # because 'each' come back 1 step when we update the entry
print "Value changed --> $key = $value\n";
} else {
print "$key = $value\n";
}
}
}
untie(%tiedHash) || die("$program_name: $dbPath: $!\n");
}
需要对每个()进行第二次调用
我必须“perl-v”:
$perl-v
这是Perl5,版本12,Subversion2(v5.12.2(*))为
amd64 openbsd(带有8个注册补丁,有关更多详细信息,请参阅perl-V)
版权所有1987-2010,拉里·沃尔
我在想如果是虫子
也许幕后还有更多的事情
我问我的解决方案是否正确?问题在于添加或删除元素(键)。更改值应该没有问题。绑定哈希没有本质上的区别
my ($key,$value);
use Tie::Hash;
tie my %fruits, 'Tie::StdHash';
%fruits = qw/ banana 1 apple 2 grape 3 /;
while ( $key = each %fruits ) {
$fruits{$key} *= 7;
print "$key = $fruits{$key}\n";
}
print "\nRead only\n\n";
while ( ($key,$value) = each %fruits ) {
print "$key = $value\n";
}
输出:
banana = 7
apple = 14
grape = 21
Read only
banana = 7
apple = 14
grape = 21
您的第二个代码片段没有演示bug。这并不能说明什么。它是不可运行的,您没有指定它输出什么,也没有指定希望它输出什么。但是让我们看看DB_文件是否有问题
use DB_File qw( $DB_BTREE );
use Fcntl qw( O_RDWR O_CREAT ); # I don't have O_EXLOCK
my ($key,$value);
tie(my %fruits, 'DB_File', '/tmp/fruits', O_RDWR|O_CREAT, 0600, $DB_BTREE)
or die $!;
%fruits = qw/ banana 1 apple 2 grape 3 /;
while ( $key = each %fruits ) {
$fruits{$key} *= 7;
print "$key = $fruits{$key}\n";
}
print "\nRead only\n\n";
while ( ($key,$value) = each %fruits ) {
print "$key = $value\n";
}
没有
很抱歉如果没有第二次调用,代码将无限期运行。我认为当它更新每个索引的值时,会后退1步。然后,下一次调用将再次获得相同的条目。我看到的是一对重复的键,用新值打印的值。预期的是一个与新值匹配的URL列表。(这是我通过第二次呼叫实现的)。ikegammi,我运行了你的代码,得到了:apple=inf apple=inf apple=inf apple=inf apple=inf apple=inf apple=inf apple=inf apple=inf apple=inf然后我运行了“perl each-ikegami.pl | head”得到了:apple=14 apple=98 apple=686 apple=4802 apple=33614 apple=235298 apple=1647086 apple=11529602 apple=80707214 apple=5649504998perl 5.16.0(线程),DB_文件1.826,伯克利DB 4.8.30(我想)
apple = 14
banana = 7
grape = 21
Read only
apple = 14
banana = 7
grape = 21