http://qs1969.pair.com?node_id=31060

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

I have been toying with references for a while now, and I bumped into something interesting. When you pass a reference to an array slice, you are not passing the list reference, but actually the references to each one of the elements in the list (please correct me if this is an incorrect statement).

To prove this, I came up with the following:
# example 1 my @ary = qw( Foo and Bar went up the Baz to fetch a Gom Jabar ); printref(\@ary[0,2,6,10,11]); sub printref { print "$$_\n" for @_; }
And it works... No problem. The I thought of doing it the other way around. First pass the array ref, and then the parameters of what you want from the array. And we have:
# example 2 my @ary = qw( Foo and Bar went up the Baz to fetch a Gom Jabar ); printref(\@ary,(0,2,6,10,11)); sub printref { my $ary = shift; print "$$ary[$_]\n" for @_; }
And again it works! Probably less efficient than the first, but still it works, no problem. Now here for the big trick that I wanted to pull off at first and obviously didn't get it to work:
# example 3 my @ary = qw( Foo and Bar went up the Baz to fetch a Gom Jabar ); printref(\@ary[0,2,6,10,11]); sub printref { my $ary = shift; print "$_\n" for @$ary; }
And we get Not an ARRAY reference at - line 13.. So after all this running around, my question is, "Is there a way to pass a reference of an array slice as a list?" Am I day dreaming again? Am I not understanding a basic concept? Any pointers in the right direction would be very appreciated.

#!/home/bbq/bin/perl
# Trust no1!

Replies are listed 'Best First'.
Re: Referencing Array Slices as Lists?
by takshaka (Friar) on Sep 05, 2000 at 12:10 UTC
    You're thinking that an array slice is itself an array, but it is actually a list. And when you take a reference to a list you get a list of references.

    Notice that a slice in scalar context acts like a list (returning the last element), not like an array (returning the number of elements):

    # perl -le '@a=(1..9); print scalar @a[2,6,5]' 6
Re: Referencing Array Slices as Lists?
by merlyn (Sage) on Sep 05, 2000 at 04:36 UTC
Re: Referencing Array Slices as Lists?
by agoth (Chaplain) on Sep 05, 2000 at 13:07 UTC
    I got a couple of good responses to an array ref question, when I was mixing lists and arrays at creating array refs.