[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Range spec to list/hash



> Several times in the recent past I have had to include or exclude
> things from a list such as records in a file, messages in a mailbox
> etc. These lists are indexed by numbers starting with 1.
> 
> The include/exclude spec is a comma separated numbers/range of numbers,
> An example: the spec 2,17,35-37,49,61-63 expands to the list of numbers
> (2, 17, 35, 36, 37, 49, 61, 62, 63).
> 
> I came up with the following ($range is expanded into @list):
> 
> @list = map {m/(\d+)\-(\d+)/ ?  ($1..$2) : $_;} split ",", $range;
> 
> On occasion I wanted it to exapnd it to a hash with the numbers as keys,
> and a true value such as 1 being the value. I augmented the above to:
> 
> %hash = map {$_ => 1} map {m/(\d+)\-(\d+)/ ?  ($1..$2) : $_;} split ",",
> $range;
> 
> I am sure that the gurus on this list can offer better solutions.
> 
> /prakash

I like your solution. Here's an alternative if you want to expand the
string without using to a list. I'm not a guru, so can't claim this is
any 'better'.

$range =~ s/(\d+)-(\d+)/join(',', ($1..$2))/ge;

Ed Perry

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe