Вопрос

I'm trying to modify an array of anonymous hashes in-place, through two subroutines:

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

The output is:

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

I expected that value_parser() modifies the data structure through the hash reference, hence in-place. Any insight would be appreciated, thanks!

Это было полезно?

Решение

You never assign $value to anything. Add

$data->{$key} = $value;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top