http://www.perlmonks.org?node_id=980835


in reply to Re^6: Perl list items
in thread Perl list items

my @c = combine(5,@n); # get array of arrays my @A = @$c[0]; # get first sub-array

Because the 'precedence' (if that's the proper term here) of the  @ array dereference sigil is so high, the expression  @$c[0] attempts to dereference an array reference held in the  $c scalar (not in the  @c array) and then access the element at index 0 in the referenced array. (Update: Actually, my first thought was that  @$c[0] would look like a 'degenerate' array slice, like @x[0]; not sure why the appropriate warning was not generated.) The expression  @{ $c[0] } is what is needed in the given example.

>perl -wMstrict -MData::Dump -le "my @c = (['x', 'y'], ['a', 'b'], ['c', 'd']); my $c = ['foo', 'bar']; ;; my @A1 = @ $c[0] ; my @A2 = @{ $c[0] }; dd \@A1; dd \@A2; " ["foo"] ["x", "y"]

Replies are listed 'Best First'.
Re^8: Perl list items
by Anonymous Monk on Jul 10, 2012 at 08:37 UTC
    To clarify  @$c[0] means the same as  @{$c}[0] meaning dereference $c, take array slice

    So

    $ perl -e " use Data::Dump; my $c = [qw/ a b c/]; dd @$c[1,2]; " ("b", "c")

    While References quick reference lists this item explicitly (item 2), its somewhat documented in perlreftut/perlref but its not recommended

      To clarify @$c[0] means the same as @{$c}[0] meaning dereference $c, take array slice

      Well... I'm not sure it's that much more clear. After all, "I know what I mean, ..."

      I'm still puzzled by the absence of a "... better written as ..." warning. Maybe the usage is just too far off the beaten track for warnings to stumble over.

      >perl -wMstrict -le "my @c = ('foo'); print @c[0]; ;; my $c = ['bar']; print @{$c}[0]; print @ $c [0]; " Scalar value @c[0] better written as $c[0] at -e line 1. foo bar bar

        I'm still puzzled by the absence of a "... better written as ..." warning.

        Because the code is different :) Because @warnme... is different from @$derefNowarn...

        For verbosity see diagnostics, try  perl -Mdiagnostics -e " @ARGV[0] "