Otherwise you are chomping every item in the array, when you know there can only be a newline at the end of the line.while (<TEST>) { my ($key,@fileData) = split /\|/; chomp @fileData; $test{$key} = \@fileData; } #to while (<TEST>) { chomp; my ($key,@fileData) = split /\|/; $test{$key} = \@fileData; }
I would change
except that that is overkill... since you can't have the multiples of the same key, you don't need to sort on the whole line, just the key, I would do...foreach my $key (keys %test) { push (@sorted, "$key|$test{$key}->[0]|$test{$key}->[1]|$test{$ke +y}->[2]|$test{$key}->[3]"); } #to foreach my $key (keys %test) { push @sorted, (join '|', ($key,@{$test{$key}}); }
Instead of the whole @sorted thingopen(TEST, ">test.txt") || die "File couldn't be opened for writing: $ +!"; foreach my $key (sort keys %test) { print TEST (join '|', ($key,@{$test{$key}}); print TEST "\n"; } close(TEST);
Update Sorry, you wanted to sort by the last item in the array of data... change
the $test{$a}[-1] <=> $test{$b}[-1] sorts numerically based on the final item in the data array at each keyforeach my $key (sort keys %test) { #to foreach my $key (sort { $test{$a}[-1] <=> $test{$b}[-1] } keys %test) +{
- Ant
In reply to Re: Learning to use the hash effectively
by suaveant
in thread Learning to use the hash effectively
by Stamp_Guy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |