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

Hi Monks, I am simply trying to use the range (..) operator to push a few elements of one array (up to a defined number) into a new array. I want to do this in one line of code as I attemped below. It's not working!! I can obviously do this quite easy with a for loop etc but want to see how this way works. Thanks a lot!
push @new_array, " $old_array[0] .. $old_array[$count] ";

Replies are listed 'Best First'.
Re: range operators
by Zaxo (Archbishop) on Jul 02, 2003 at 10:53 UTC

    The push operator can take a list in the second argument. What you want is a slice of @old_array:

    push @new_array, $count > @old_array ? @old__array : @old_array[0 .. $count-1];
    That checks the size of @old_array to see if it has at least $count elements. If less or equal, the whole array is pushed without padding, otherwise the slice of the first $count elements is pushed.

    After Compline,
    Zaxo

Re: range operators
by cchampion (Curate) on Jul 02, 2003 at 10:54 UTC

    You can use a slice

    perl -e '@x=(qw(a b c d e f g)); push @y, @x[2..3]; print "@y\n"' c d

    update

    Damn!. A few moments spent to approve the node made the difference. Zaxo anticipated me by a split second! :)

Re: range operators
by tbone1 (Monsignor) on Jul 02, 2003 at 15:22 UTC
    I think the problem is the double quotes, try using parentheses instead, like this.

    #! /bin/perl @ar=(3,8); push @new_array, ($ar[0] .. $ar[1]); foreach ( @new_array) { print "$_\n"; }
    This gives an array with elements 3,4,5,6,7,8.

    --
    tbone1
    Ain't enough 'O's in 'stoopid' to describe that guy.
    - Dave "the King" Wilson