In case the subject isn't entirely clear, what I'm trying to achieve is a sort of an array of hashes by a field which contains the following three keywords -- Local, State, National. The trick is that I need to sort the records in that order. Thus a straight-forward alpha sort will not work.

I checked the Q&A, searched PM and Google and checked my various Perl books to no avail. I have a solution but am hoping a more clever monk could make it more efficient.

#!/usr/bin/perl use strict; use Data::Dumper; my @advocates = ( { fld_title => 'Rec1', fld_type => 'National', }, { fld_title => 'Rec2', fld_type => 'State', }, { fld_title => 'Rec3', fld_type => 'Local', }, ); sub by_locale { my $a_type; my $b_type; $a_type = 1 if ($a->{'fld_type'} =~ /local/i); $a_type = 2 if ($a->{'fld_type'} =~ /state/i); $a_type = 3 if ($a->{'fld_type'} =~ /national/i); $b_type = 1 if ($b->{'fld_type'} =~ /local/i); $b_type = 2 if ($b->{'fld_type'} =~ /state/i); $b_type = 3 if ($b->{'fld_type'} =~ /national/i); $a_type <=> $b_type; } my @sorted_advocates = sort by_locale @advocates; warn Dumper("unsorted_advocates", \@advocates); warn Dumper("sorted_advocates", \@sorted_advocates);

Thanks for any pointers,

-Wm

In reply to Efficiently sorting array by non-alpha strings by knowmad

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.