in reply to Re^3: Replace a value with another value from the same array
in thread Replace a value with another value from the same array

No, it can be done in one pass quite easily — you might not even need to pass through the whole array once.

my ($xxy, $yyk); for (@$data) { $xxy = $_ if $_->{code} eq 'XXY'; $yyk = $_ if $_->{code} eq 'YYK'; if ($xxy && $yyk) { $yyk->{expdate} = $xxy->{expdate}; last; } }

Replies are listed 'Best First'.
Re^5: Replace a value with another value from the same array
by huck (Prior) on May 09, 2017 at 21:49 UTC

    It was not specified that there would only be one YYK entry, and if there were multiples and they all came before the XXY was found only the last found would be replaced, or only the first if any came after the XXY entry.

      If there are multiple YYK entries, my code still works. It'll just use the first one it finds. If you'd rather use the last YYK entry then just comment out:

      last;

      And you still only have a single pass.

        use strict; use warnings; my $data=[]; $data->[0]={code=>'YYK',expdate=>'fixme'}; $data->[1]={code=>'YYK',expdate=>'fixme'}; $data->[2]={code=>'YYK',expdate=>'fixme'}; $data->[3]={code=>'YYK',expdate=>'fixme'}; $data->[4]={code=>'YYK',expdate=>'fixme'}; $data->[5]={code=>'XXY',expdate=>'fixer'}; $data->[6]={code=>'YYK',expdate=>'fixme'}; $data->[7]={code=>'YYK',expdate=>'fixme'}; my ($xxy, $yyk); for (@$data) { $xxy = $_ if $_->{code} eq 'XXY'; $yyk = $_ if $_->{code} eq 'YYK'; if ($xxy && $yyk) { $yyk->{expdate} = $xxy->{expdate}; last; } } use Data::Dumper; print Dumper($data);
        $VAR1 = [ { 'expdate' => 'fixme', 'code' => 'YYK' }, { 'code' => 'YYK', 'expdate' => 'fixme' }, { 'expdate' => 'fixme', 'code' => 'YYK' }, { 'expdate' => 'fixme', 'code' => 'YYK' }, { 'expdate' => 'fixer', 'code' => 'YYK' }, { 'code' => 'XXY', 'expdate' => 'fixer' }, { 'code' => 'YYK', 'expdate' => 'fixme' }, { 'expdate' => 'fixme', 'code' => 'YYK' } ];
        Wasnt the first one it found in index 0?