如果我们更改/更新每个循环中的哈希值,会发生什么



'perldoc -f每个'说我在迭代时不安全删除或添加值,除非该项目是每个()最近返回的()。

运行此代码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 onlynn";
while ( ($key,$value) = each %fruits ) {
    print "$key = $valuen";
}

一切正常!

,但是如果我使用绑带的哈希,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 = $valuen";
            } else {
                print "$key = $valuen";
            }
        }
    }
    untie(%tiedHash) ||  die("$program_name: $dbPath: $!n");
}

是对每个()的第二个调用。

我必须'perl -v':

$ perl -v

这是perl 5,版本12,颠覆2(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 onlynn";
while ( ($key,$value) = each %fruits ) {
    print "$key = $valuen";
}

输出:

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 onlynn";
while ( ($key,$value) = each %fruits ) {
    print "$key = $valuen";
}

nope。

apple = 14
banana = 7
grape = 21
Read only
apple = 14
banana = 7
grape = 21

最新更新