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

Are the elements in the array always in this order, i.e. XXY comes before YYK? If yes, then why don't you just remove the reverse from foreach my $all_item (reverse @{ $all })? Then it works for me.

If the order of the data can change, then what the easiest way to solve it is depends on how big the input data can get - if it's always small, then you can just loop over the data array twice, once to get the value from XXY and once to save it to YYK.

Replies are listed 'Best First'.
Re^2: Replace a value with another value from the same array
by Anonymous Monk on May 09, 2017 at 19:36 UTC
    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.

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

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