in reply to compare previous and present hash key values

The way I understand the question, you are needing to compare all pairs of neighboring keys.

The problem is that hashes do not preserve order, you need an array @result for that or you have to store the order of keys separately in an array @order.¹

that's one way to go pairwise:

DB<120> @order=1..5 => (1, 2, 3, 4, 5) DB<121> $last= $order[0] => 1 DB<122> for $cur (@order[1..$#order]) { print "$last,$cur\t"; $last =$cur; } => "" 1,2 2,3 3,4 4,5

edit

For completeness, a shorter but trickier way, using reduce:

DB<126> use List::Util qw/reduce/ DB<127> reduce { print "$a,$b\n"; $b } @order 1,2 2,3 3,4 4,5

HTH! =)

Cheers Rolf

( addicted to the Perl Programming Language)

update

¹) e.g.

while ( my $rec = $data->fetchrow_hashref ) { push @{ $result{ $rec->{"ID"} } }, $rec->{"item"}; push @order, $rec->{ID}; }

Replies are listed 'Best First'.
Re^2: compare previous and present hash key values
by undisputed (Initiate) on Jan 11, 2014 at 16:03 UTC

    I just converted the hash into an array sorted

    using:
    my @array = map { $result{$_} } sort { $a<=>$b } keys %result;

    Since it's now an array, how may i proceed ?

    This is the print of the array sorted without keys though:

    $VAR1 = [ [ '172193', '19601', '14835', '16718' ], [ '172193', '19601', '14835', '16718' ], [ '172193', '19601', '14835', '16718' ], [ '172193', '19601', '14835', '16718' ], continues....

    for now they all look the same but as it progresses there are differences

    I don't understand your code well, also the lines of code added to your code confuses.

      OK once again...

      ( supposing that the numerical order of IDs is not the compare order you want, but that you still need the ID for further evaluation)

      do this to keep record of the order of the keys

      my %order; while ( my $rec = $data->fetchrow_hashref ) { push @{ $result{ $rec->{"ID"} } }, $rec->{"item"}; push @order, $rec->{ID}; # read order }

      and do this to compare the neighboring keys

      my $last = $order[0]; # first key for my $cur ( @order[1..$#order] ) { # following key +s compare($last,$cur); $last = $cur; # keep current +as last }

      plz note: compare() is a sub you have to provide, you said "this i know how to".

      Within compare you can access the values of the hash '%result' with the neighboring keys '$last' and '$cur'.

      like

      sub compare { my ($previous,$present) = @_; ... }

      Cheers Rolf

      ( addicted to the Perl Programming Language)