Re: Hash Sorting Problem



Anirban Adhikary wrote:
Dear List

Hello,

I have written the following code .............

use Data::Dumper;


%file = (14 => "GGG",
11 => "AAA",
101 => "EEE",
1 => "TTT");


print Dumper \%file;



@arr1 = sort { $file{$b} cmp $file{$a} } keys %file; #the oldest entry lies
at the top position

print Dumper \@arr1;

foreach $el(@arr1)
{

delete $file{$el};
print "The $el is removed from the sorted list"."\n";
@arr1 = sort { $file{$b} cmp $file{$a} } keys %file; #the oldest entry lies

perldoc perlsyn
[ SNIP ]
If any part of LIST is an array, "foreach" will get very confused if
you add or remove elements within the loop body, for example with
"splice". So don’t do that.


at the top position
print "After sorting the array elements are"."\n";
print Dumper \@arr1;
}


---------------output ------------

$VAR1 = {
'1' => 'TTT',
'11' => 'AAA',
'101' => 'EEE',
'14' => 'GGG'
};
$VAR1 = [
'1',
'14',
'101',
'11'
];
The 1 is removed from the sorted list
After sorting the array elements are
$VAR1 = [
'14',
'101',
'11'
];
The 101 is removed from the sorted list
After sorting the array elements are
$VAR1 = [
'14',
'11'
];

In the last output I think the list is not sorted properly. How can I solve
this problem.

It is sorted properly, it's just that you are modifying the array @arr1 inside a foreach loop that iterates over that same array and you shouldn't do that.



John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall

.



Relevant Pages

  • problem with play AOA
    ... I try to slice AOA into two subsets, ... Here is Original array ... print Dumper of array B ... foreach my $i { ...
    (perl.beginners)
  • Hash Sorting Problem
    ... foreach $el ... After sorting the array elements are ...
    (perl.beginners)
  • RE: [PHP] How to get the key of a specific index of array?
    ... you said to use the first three values of the array for anoter ... with a $_POST array you can do foreach with. ... don't rely on the order your array elements are given to you by post ...
    (php.general)
  • Re: [PHP] foreach() using current() strange beahvior
    ... that's expected as foreach moves the internal array pointer, ... When using the internal pointer just by calling current(so not moving ... Unless the array is referenced, foreach operates on a copy of the ...
    (php.general)
  • Re: a question about for and foreach
    ... foreach (@array) { ... why @array are changed after this foreach loop!!! ... The "foreach" loop iterates over a normal list value and sets the ... If any element of LIST is an lvalue, you can modify it by modifying ...
    (perl.beginners)