You're splitting the line on commas (after changing tabs to commas, which is puzzling), then saving each line in a hash with the key being the first element from your split. So the hash key that you're sorting by is that first column. If you want to sort by something else, you have to tell the sort function that.

To make another column easily available to sort, and to avoid duplicating work you've already done, save @columns in your hash instead of the original line. Then you'll have a hash of arrays, so you can sort on whichever element of the array you'd like:

$tag{$columns[0]} = \@columns; } foreach my $tags ( sort { $tag{$a}[1] <=> $tag{$b}[1] } keys %tag ){

In this case, I'm using <=> to sort numerically, based on the second element of the array pointed to by each hash key's value. To sort alphabetically, change <=> to cmp. Now you can get your array back into @columns with the dereference @{$tag{$tags}}, so you don't have to re-split your line.

One concern: you said you're trying to come up with a unique key for each line, but you're using the first column alone as the key when you put them in the hash. If the values from the first column aren't already unique, you'll be overwriting values there, so lines will already be missing by the time you sort and start adding your other parts. If you need to add the frequency and a random number to get a unique key (and I have a feeling there's a better way to do that than with random numbers, which could repeat), you should do that before you save the key in your hash.


In reply to Re: Sorting issue by aaron_baugher
in thread Sorting issue by bluray

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.