Re: Hash Sorting Problem
- From: anirban.adhikary@xxxxxxxxx (Anirban Adhikary)
- Date: Mon, 25 Feb 2008 15:02:42 +0530
Dear List
I need to delete each element after every execution of the foreach loop and
I need to update & sorted the @arr1 after every execution of the foreach
loop. I have tried a lot but not able to do this ............Pls
help...........
Thanks & Regards
Anirban Adhikary
On Mon, Feb 25, 2008 at 1:51 PM, John W. Krahn <krahnj@xxxxxxxxx> wrote:
Anirban Adhikary wrote:
Dear List
Hello,
I have written the following code .............lies
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
at the top positionlies
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
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 positionsolve
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
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
--
To unsubscribe, e-mail: beginners-unsubscribe@xxxxxxxx
For additional commands, e-mail: beginners-help@xxxxxxxx
http://learn.perl.org/
- Follow-Ups:
- Re: Hash Sorting Problem
- From: Chas. Owens
- Re: Hash Sorting Problem
- From: Mk
- Re: Hash Sorting Problem
- References:
- Hash Sorting Problem
- From: Anirban Adhikary
- Re: Hash Sorting Problem
- From: John W. Krahn
- Hash Sorting Problem
- Prev by Date: Re: Hash Sorting Problem
- Next by Date: Re: Hash Sorting Problem
- Previous by thread: Re: Hash Sorting Problem
- Next by thread: Re: Hash Sorting Problem
- Index(es):
Relevant Pages
|