Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Perl Module for dealing with number ranges

by dmmiller2k (Chaplain)
on Jun 05, 2009 at 18:30 UTC ( [id://768876]=note: print w/replies, xml ) Need Help??


in reply to Perl Module for dealing with number ranges

I recently had this same problem. Not realizing there might be a CPAN module (I know, I know, what was I thinking?), I came up with this sub:

sub expandlist { local $" = '..'; # locally set list separator my (@parts); sort {$a <=> $b} map { map { ((@parts = split /-/) == 2) ? eval('map {$_} '. "@parts") : $_ } split /,/ } @_; }

Briefly:

  • The outer map loops through all function args (usually only called with one). For each arg, split on commas.
  • Try to split each element originally separated by commas, on hyphens.
  • If splitting on hyphens produces exactly two elements in @parts, interpolate the array into a string (with the list separator set to '..'), turning, e.g., '6-9' into '6..9' which is appended to 'map {$_}' and that whole thing eval'ed, ultimately producing a list of elements: 6, 7, 8, 9
  • The elements are all gathered and combined and sorted.

Crude and hardly idiot-proofed, but it works without having to get a CPAN module installed on all our servers.

dmm

Procrastinate NOW! Don't put it off... --Ellen Degeneres

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-19 16:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found