Hi, I have a subroutine that sorts a passed array. The array elements are hash references resulting from a "selectall_arrayref" DBI query against a SQL db. The sort routine selects the sort method (via separate subs) based on input flags. One of the fields I sort with is a "date" field where the dates come in the format "YYYY.MM.DD". I want to numerically sort these, which requires stripping the periods before passing into the sort. Here is what I have now:
sub sort_records {
my $sort_routine;
($opt_g =~ /^t/i) ? #flag setting sort order
($sort_routine = \&sort_by_title) :
($sort_routine = \&sort_by_date);
foreach (@_) {
($_->{'cleandate'} = $_->{'date'}) =~ s/\D//g;
} #do I need this?
my @records = map { $_->[0] }
sort $sort_routine
map { [ $_, $_->{'title'}, $_->{'cleandate'} ] }
# or can I do it here?
@_;
return @records;
}
(The sort_by_title and sort_by_date subs are basic sort functions straight from the perl cookbook. Only difference is the order in which they compare the fields).
So my question is, can I get rid of the "foreach" loop and somehow do the same thing right in the map, but without changing the values in the source?
(Any other critiques/suggestions also welcome).
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.