2

我正在尝试通过两个子例程就地修改一组匿名哈希:

my $hashes = [{
    foo => 'bar',
    foobar => 'baz',
    qux => { 'foo' => 'baz' },
}];

sub data_parser
{
    my $data = shift;

    while ((my $key, my $value) = each($data)) {
            if (ref($value) ne '') {
                    __SUB__->($value);
            } else {
                    $value = value_parser($value)  if ($key eq 'foo');
                    print "data_parser() ${key}'s new value is: ${value}\n"  if ($key eq 'foo');
            }
    }
}

sub value_parser { return('newvalue'); }

foreach my $hash (@{$hashes}) {
    data_parser($hash);
    print "foo is " . $hash->{'foo'} . "\n";
    print "foo is " . $hash->{'qux'}{'foo'} . "\n";
}

输出是:

data_parser() foo's new value is: newvalue
data_parser() foo's new value is: newvalue
foo is bar
foo is baz

我期望 value_parser() 通过哈希引用修改数据结构,因此就地。任何见解将不胜感激,谢谢!

4

1 回答 1

3

你永远不会分配$value给任何东西。添加

$data->{$key} = $value;
于 2013-10-25T13:03:25.800 回答