my @SortedKeys = sort {$field{$a} cmp $field{$b}} keys %fields;
We are creating our own sort routine, where we can use the keys in the %fields hash, but compare the values belonging to those keys to perform the sort.

This will cause a lot of hash lookups, but my benchmarks show that hash lookups are not expensive enough to warrant a Schwartzian Transform.

<Update> Oops, didn't read the question</Update>

my @SplitEntries = map{[split( '|', $_)]} @Entries; foreach $Lineref (sort {$a->[8] cmp $b->[8]} @SplitEntries) { my @Fields = @$Lineref; # This will be in sorted order, by Artist Name # $Fields[0] is CassID, $Fields[1] is CDID, etc }
New explanation: We create arrays of fields from each line, storing them in @SplitEntries (each entry in @SplitEntries is an arrayref holding the fields).

Now, we can sort the entries on Artist Name.

This is not the most CPU-efficient way to do this, either. If your music database is really big, you may want to get the Artist Name for each entry and the array index of its line. Then, sort the names and use the indices to get back to the real array.

my @SplitEntries = map{[split( '|', $_)]} @Entries; my @Names = map{[$_, @SplitEntries[$_]]} @SplitEntries; my @SortedIndices = map {$_->[0]} sort {$a->[1] cmp $b->[1]} @Names; foreach $lineref (@SplitEntries{@SortedIndices}){ my @Fields = @$Lineref; ... }
Even better, you should consider using DBI and let it manage your sorting needs. ;-)

Russ
Brainbench 'Most Valuable Professional' for Perl


In reply to Re: Sorting on a particular field from a Flat File db?? by Russ
in thread Sorting on a particular field from a Flat File db?? by Anonymous Monk

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.