gpt4 book ai didi

perl - 如果我们更改/更新每个循环内的哈希值会发生什么?

转载 作者:行者123 更新时间:2023-12-01 04:50:45 25 4
gpt4 key购买 nike

'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\n";

while ( ($key,$value) = each %fruits ) {
print "$key = $value\n";
}

一切正常!

但是如果我使用绑定(bind)哈希,哼哼:

#-------------------------------------------------------------------------------
# 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");
}

有必要对 each() 进行第二次调用。

我必须“perl -v”:

$ perl -v

This is perl 5, version 12, subversion 2 (v5.12.2 (*)) built for amd64-openbsd (with 8 registered patches, see perl -V for more detail)

Copyright 1987-2010, Larry Wall ...

我在想这是否是一个错误?!!

也许幕后还有更多的事情......

请问我的解决方案是否正确???

最佳答案

问题在于添加或删除元素(键)。更改值应该没有问题。与绑定(bind)哈希没有内在区别。

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

您的第二个片段没有展示错误。它没有展示任何东西。它不可运行,您没有指定它输出什么,也没有指定您期望它输出什么。但是让我们看看 DB_File 是否有问题。

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";
}

没有。

apple = 14
banana = 7
grape = 21

Read only

apple = 14
banana = 7
grape = 21

关于perl - 如果我们更改/更新每个循环内的哈希值会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13035823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com