Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: manipulating array (TMTOWTDI!)

by Codon (Friar)
on Aug 23, 2007 at 19:59 UTC ( [id://634720]=note: print w/replies, xml ) Need Help??


in reply to manipulating array

If you know that every element begins with the A19\d+ (or you only care about these lines) you can filter / clean the records with a grep. You can then pipe those (matched/cleaned) items to sort (via a Schwartzian Transform) using a quick (simple) by_date subroutine.

#!/usr/bin/perl use strict; use warnings; my @data = <DATA>; print "data\n"; print @data; my @sorted = # do a little transform map { join(' ', @$_) } # join sort { &by_date($a, $b) } # sort map { [ split / /, $_ ] } # split grep { s/^A\d+ // } # clean @data; print "sorted\n"; print @sorted; sub by_date { my($a_mon,$a_day,$a_year) = split m[/], $a->[1]; my($b_mon,$b_day,$b_year) = split m[/], $b->[1]; return ($a_year <=> $b_year or $a_mon <=> $b_mon or $a_day <=> $b_ +day); } __DATA__ A19234 hostname 06/08/07 moredata moredata A19284 hostname 07/09/07 moredata moredata A19384 hostname 06/06/06 moredata moredata A19234 hostname 07/08/07 moredata moredata A19284 hostname 07/09/07 moredata moredata A19384 hostname 06/09/07 moredata moredata A19234 hostname 07/06/06 moredata moredata A19284 hostname 07/09/07 moredata moredata A19384 hostname 06/09/07 moredata moredata

I know I could have saved some characters on the sort line, but this was more aesthetically pleasing to me.

Ivan Heffner
Sr. Software Engineer
WhitePages.com, Inc.

Replies are listed 'Best First'.
Re^2: manipulating array (TMTOWTDI!)
by ikegami (Patriarch) on Aug 23, 2007 at 20:44 UTC
    I don't like how it not only clobbers @data, but relies on it. The grep could be replaced with:
    map { local $_ = $_; s/^A\d+ // ? $_ : () }
The big point, too...
by chaggalag (Initiate) on Aug 24, 2007 at 07:59 UTC
    I like that solution because it points out the most significant lesson: that "*" has a specific meaning the original poster did not want.

    The star means "zero or any repeats of the previous item" in a regex context. The specific string one wants to match is "the letter A followed by the numbers 1 then 9 followed by two digits of the 0 through 9 series followed by a 4...".

    It's very important to take the time to think about a regex in that plodding way or you get matches you won't want. For example, the rest of the line could match.

    I hope I'm not being redundant with my bandwidth. Y'all have a good day.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://634720]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-29 10:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found