3

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

当我运行此代码片段时:

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

一切正常!

但是,如果我使用绑定哈希,嗯:

#-------------------------------------------------------------------------------
# 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

这是为 amd64-openbsd 构建的 perl 5,版本 12,subversion 2 (v5.12.2 (*))(带有 8 个已注册补丁,有关更多详细信息,请参见 perl -V)

版权所有 1987-2010,拉里·沃尔...

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

也许更多的事情在幕后......

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

4

1 回答 1

3

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

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
于 2012-10-23T17:40:17.017 回答