In one of my scripts I currently have a section similar to the following so that I can sort strings numerically, rather than alphabetically:
# sample data my %network = ( 10.1.0.1, { 'name' => 'vlan 2' } 10.2.0.2, { 'name' => 'vlan 3' } ); foreach my $network (sort { by_num($networks{$a}->{'name'}) <=> by_num +($networks{$b}->{'name'}) or $a cmp $b } keys %networks ) { # do stuff... } # Extract the number from a string # Used to sort Network names by vlan number, rather than alphabeticall +y sub by_num { my $key = shift; $key =~ /(\d+)/; return $1; }
I would like to add something to the top of the script to make sorting alphabetically or numerically an option, and I was hoping to consult the monks for an elegant solution. I thought maybe I could use anonymous subroutines...
#### untested/concept code below # set the following to either 'alpha' or 'num' $sortby= 'alpha'; my %sort_network; $sort_network{'alpha'} = sub { $a->{'name'} cmp $b->{'name'} }; $sort_network{'num'} = sub { by_num($a->{'name'}) <=> by_num($b->{'nam +e'} ) or $a->{'name'} cmp $b->{'name'}; foreach my $network (sort &$sort_network{$sortby} keys %networks ) { # do stuff... }
I think this should work, but I was wondering if there might be a more obvious/elegant solution.

In reply to Variable Subroutine by tombmbdil

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.