John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:

What is the syntax to take a slice of a list reference? The following gives me Argument "" isn't numeric in array element with the warning message indicating the @left= line.

my ($self, $n)= @_; my $len= scalar @$self; print " *** n=$n, len=$len\n"; my @left= $self->[0..$n-1]; my @right= $self->[$n..$len-1];
The print indicates that n=1, and len=6. $self is [1, 2, 3, 4, 5, 6] using BigInt's.

What I want to do is put n items in @left and the remaining items in @right.

—John

Replies are listed 'Best First'.
Re: Still slice impared
by davido (Cardinal) on Feb 24, 2004 at 06:22 UTC
    If $self is an array-ref...

    my @slice = @{$self}[0..$n-1];

    That ought to do it. The curly brackets are being used in this case for clarity. It can also be expressed like this:

    my @slice = @$self[0..$n-1];

    ....at least in my test cases that seems to work just fine. ;)


    Dave

      Thanks.

      In my code, the actual results indicate that the array indexing takes the first element of the list only. But, any idea where the warning about "" not being a numeric argument could be coming from?

        From the ".." flipflop operator in scalar context.
Re: Still slice impared
by Enlil (Parson) on Feb 24, 2004 at 06:35 UTC

    davido, answered your question. but here is another way to do it (TIMTOWTDI and all that).

    What I want to do is put n items in @left and the remaining items in @right.

    my (@right, @left); (@left[0 .. $n - 1], @right) = @$self;

    -enlil

Re: Still slice impared
by revdiablo (Prior) on Feb 24, 2004 at 18:40 UTC
    a slice of a list reference

    Hate to be nitpicky (and the question has already been answered sufficiently), but there's no such thing as a list reference. That would be an array reference. A list is not a type of variable, whereas an array is. So you can only take a reference to an array, not a list.