Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there, I've got the below value assigned to a variable that was read in from a file:

$ips="30..39,50..59";

I want to declare an array using this variable so that the range operators and commas are interpreted like this:

@array=(30..39,50..59);

Thus the ".."'s become interpreted as a range operator and the array is initialized with the number values 30 through 39, and 50 through 59 inclusive.

@array[0]=30; @array[1]=31; @array[2]=32;
etc.

Doing the below initialization doesn't get my desired result.
@array=($ips); @array=("$ips");
Instead the array value is explicitly set to the string "30..39,50..59".

How would one achieve this? None of the typecasting or quoting articles I found addressed this.

Thanks!
- Andrew

Replies are listed 'Best First'.
Re: Declare array with range operator
by BrowserUk (Patriarch) on Jul 12, 2011 at 19:06 UTC

    If you trust the source, then eval:

    c:\test>p1 $ips="30..39,50..59";; @array= eval $ips;; print "@array";; 30 31 32 33 34 35 36 37 38 39 50 51 52 53 54 55 56 57 58 59

    otherwise parse:

    @a = map{ my( $s, $e ) = split '\.\.'; $s .. $e } split ',', $ips;; print "@a";; 30 31 32 33 34 35 36 37 38 39 50 51 52 53 54 55 56 57 58 59

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Thank you for the prompt response. This is exactly what I was looking for, thanks!

Re: Declare array with range operator
by Anonymous Monk on Jul 12, 2011 at 19:12 UTC

    Doing the below initialization doesn't get my desired result.

    You're essentially doing @array = ( "string" ); </C> The operator, is double quotes "", you want to use the range operator, so

    my $range = "1..3,7..9"; my @array; while($range =~ /(\d+)\.\.(\d+)/g ){ my( $left , $right ) = ( $1, $2 ); push @array, $left .. $right; } print "@array\n"; __END__ 1 2 3 7 8 9

    "1..3,7..9" is data and 1..3,7..9 is code

Re: Declare array with range operator
by zek152 (Pilgrim) on Jul 12, 2011 at 19:09 UTC

    There might be a better way to do this but I would just parse the string.

    $ips = "30..39,50..59,20..25"; @array; #while there are more ranges in the string while($ips =~ s/(\d+)\.\.(\d+),?(.*)/$3/) { #loop over the range for $num ($1 .. $2) { push @array, $num; } } for(@array) { print $_ . " "; } print "\n"; #OUTPUT #30 31 32 33 34 35 36 37 38 39 50 51 52 53 54 55 56 57 58 59 20 21 22 +23 24 25 #