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

This question was already asked here but my brain didn't digest it very well.

The following bit works fine:

while(<FILE>) { $entry = [ split /\t/ ]; push @ip_time, [$entry->[0], $entry->[9]];

but...

push @ip_time, [$entry->[0, 9]];

...doesn't. Nor does this...

push @ip_time, [@$entry->[0, 9]];

...and I tried about a dozen other iterations. I'm out of ideas. Can someone spell this out for me?

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop";
$nysus = $PM . $MCF;
Click here if you love Perl Monks

Replies are listed 'Best First'.
Re: Slice of an array of an array
by wog (Curate) on Jul 04, 2001 at 04:45 UTC
    The syntax is @{$entry}[0,9], or @$entry[0,9].

    Where ever you use the name of a "real" array, you can use curly brackets and an array reference, and those curly brackets are optional when perl will not interpert your code as dereferencing something else, etc. (Similarly, you can use $#$arrayref or $#{$arrayref} for an equivelent of $#array.) The -> syntax is an alternative to ${$arrayref}[$i] (or $$arrayref[$i], and looks much cleaner, in my opinion. Unfortunatly there does not seem to be a similar syntax for hashref slices.

    (note that a similar rule can be applied to hashrefs.)

    update: s/(brackets)/curly $1/g

Re: Slice of an array of an array
by toma (Vicar) on Jul 04, 2001 at 04:49 UTC
    You can just push the scalar array reference if you want the whole array:
    push @ip_time, $entry;
    Or you can skip the variable altogether and use:
    push @ip_time, [ split /,/ ];
    Here is the complete example with the slices:
    use strict; use Data::Dumper; my $entry; my @ip_time; $_= "a,b,c,d,e,f"; $entry = [ split /,/ ]; push @ip_time, $entry; # This does the whole array $_= "g,h,i,j,k,l"; push @ip_time, [ split /,/ ]; # This does the whole array push @ip_time, [@{[ split /,/ ]}[0,5]]; # Slice it! push @ip_time, [(split /,/ )[0,5]]; # This works, too $_= "m,n,o,p,q,r"; $entry = [ split /,/ ]; push @ip_time, [ @{$entry}[0,5] ]; print Dumper(@ip_time);

    Update: fixed per wog's recommendation

    It should work perfectly the first time! - toma

Re: Slice of an array of an array
by John M. Dlugosz (Monsignor) on Jul 04, 2001 at 08:13 UTC
    Hmm, as I grok it, the slice doesn't work on a reference (that is, after the arrow). So try (@$entry)[0,9] with no arrow and see how that works (I think the parens are not needed either; just pointing out the precedence.