First of all change
while (<TEST>) { my ($key,@fileData) = split /\|/; chomp @fileData; $test{$key} = \@fileData; } #to while (<TEST>) { chomp; my ($key,@fileData) = split /\|/; $test{$key} = \@fileData; }
Otherwise you are chomping every item in the array, when you know there can only be a newline at the end of the line.

I would change

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}}); }
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...
open(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);
Instead of the whole @sorted thing

Update Sorry, you wanted to sort by the last item in the array of data... change

foreach my $key (sort keys %test) { #to foreach my $key (sort { $test{$a}[-1] <=> $test{$b}[-1] } keys %test) +{
the $test{$a}[-1] <=> $test{$b}[-1] sorts numerically based on the final item in the data array at each key
Untested, but I believe it all works fine

                - Ant


In reply to Re: Learning to use the hash effectively by suaveant
in thread Learning to use the hash effectively by Stamp_Guy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.