in reply to need help to split list

A bit longer than BrowserUK's approach, but probably easier to understand and a bit more robust:

#!/usr/bin/perl use strict; my $list = '1-5,6a-e,7,10-13'; my @list = split(/\s*,\s*/, $list); print join("\n", expand($_)), "\n" foreach @list; sub expand { my $str = shift; if ($str =~ /^(\d+)\-(\d+)$/) { return ($1..$2); } elsif ($str =~ /^(\d+)([a-z]+)\-([a-z]+)$/) { return map {$1.$_} ($2..$3); } elsif ($str =~ /^\d+$/) { return $str; } else {f die("wrong format"); } }
Note that it doesn't check whether the ranges are valid, e.g. whether $1 <= $2, but that's trivial to add.

Hope this helps, -gjb-

Replies are listed 'Best First'.
Re: Re: need help to split list
by bfdi533 (Friar) on Oct 26, 2003 at 22:47 UTC
    Quite good and very readable! Thanks.