in reply to array pushing
If have you a hash like so:
And you want to sort it by the values, then you shouldn't use a while loop with each. Instead, use a for loop with sort and keys.my %word = ( 'list' => 3, 'thats' => 1, 'value' => 2, 'an' => 1, 'would' => 1, 'the' => 3, 'at' => 1, 'if' => 2, );
First example - i want to print the above hash sorted by the keys in ascending order:
Second example - sort by the values in ascending order:print "$_ => $word{$_}\n" for sort keys %word;
What's going on with $a and $b? Those are special built-in variables used for sorting. You should read the docs on sort. Moving on:print "$_ => $word{$_}\n" for sort {$word{$a} <=> $word{$b}} keys %word;
Third example - sort first by the values in descending order this time, and then sort by the keys in ascending order:
Finally, here is a complete script for your amusement. It reads in some text from the DATA filehandle (for convenience) and tries to filter out "words". These "words" are stored into a hash, and the 'histogram' is printed out and the end. The mystery of $blank is up to you to solve. ;)print "$_ => $word{$_}\n" for sort { $word{$b} <=> $word{$a} # sort values desc || # if same, then $a cmp $b # sort keys asc } keys %word ;
use strict; use warnings; my %word; while (<DATA>) { $word{"\L$_"}++ for map {s/\W//g;$_} split; } my $blank = delete $word{''}; printf("% 14s => %d\n",$_,$word{$_}) for sort { $word{$b} <=> $word{$a} # sort values desc || # if same, then $a cmp $b # sort keys asc } keys %word ; print "$blank 'errors' encountered\n"; __DATA__ I'm having a little trouble following the documentation on pushing. It gives us the example: for $value (LIST) { $ARRAY[++$#ARRAY] = $value; } I'm assuming (LIST) should be an array list, and if that's so it would have been nice if they said that in the docs because at first I thought it was a filehandle of some kind.
jeffa
L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high-hat)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (jeffa) Re: array pushing
by sulfericacid (Deacon) on Apr 26, 2003 at 16:56 UTC | |
by jeffa (Bishop) on Apr 27, 2003 at 17:31 UTC |