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

No, it isn't in this order and I need to use "reverse" for other proposes. The data varies in size and it can get bigger.
  • Comment on Re^2: Replace a value with another value from the same array

Replies are listed 'Best First'.
Re^3: Replace a value with another value from the same array
by haukex (Archbishop) on May 09, 2017 at 19:41 UTC

    Ok, here's a solution that does it on a single pass regardless of order, it takes advantage of the fact that the array elements are references to the anonymous hashes (perlreftut, perlref, perldsc):

    my ($source,$target); for my $item (@$all) { if ( $item->{code} eq 'XXY' ) { $source = $item; $target->{expdate} = $item->{expdate} if defined $target; } if ( $item->{code} eq 'YYK' ) { $target = $item; $item->{expdate} = $source->{expdate} if defined $source; } }
Re^3: Replace a value with another value from the same array
by huck (Prior) on May 09, 2017 at 19:42 UTC

    I think you are going to need two passes since you imply you cannot insure the order of the 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; } }

        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.