Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^7: Perl list items

by AnomalousMonk (Monsignor)
on Jul 10, 2012 at 07:51 UTC ( #980835=note: print w/ replies, xml ) Need Help??


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"]


Comment on Re^7: Perl list items
Select or Download Code
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] "

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://980835]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2014-07-11 00:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls