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

The following code works:

File name: test.pl
#!/usr/bin/perl use strict; use warnings; my $res = { 'objects'=>[ {'a'=>'1', b=>'2'} ] }; my $arr = $res->{objects}; for my $elem (@$arr) { print $elem->{a}."\n"; print $elem->{b}."\n"; }

But this code doesn't work:

File name: test2.pl
#!/usr/bin/perl use strict; use warnings; my $res = { 'objects'=>[ {'a'=>'1', b=>'2'} ] }; for my $elem (@$res->{objects}) { print $elem->{a}."\n"; print $elem->{b}."\n"; }

The error message I get says the following:

Not an ARRAY reference at test2.pl line 7.

How can I do this without making the copy using the intermediate $arr variable?


Thanks.

Replies are listed 'Best First'.
Re: Referring to an array without copying to a separate variable first
by keszler (Priest) on Jun 26, 2013 at 21:58 UTC
    #!/usr/bin/perl use strict; use warnings; my $res = { 'objects'=>[ {'a'=>'1', b=>'2'} ] }; for my $elem ( @{$res->{objects}} ) { print $elem->{a}."\n"; print $elem->{b}."\n"; }
    Note that @{$res->{objects}} and @$res->{objects} are not the same.
      little addendum:

      > Note that @{$res->{objects}} and @$res->{objects} are not the same.

      ... b/c of Perl's precedence rules:

      @$res->{objects} means @{$res}->{objects} which doesn't make sense.

      Cheers Rolf

      ( addicted to the Perl Programming Language)

        "@$res->{objects} means @{$res}->{objects} which doesn't make sense."

        It doesn't make sense to me either but B::Deparse seems to know what's going on:

        $ perl -MO=Deparse,p -e '@{$res}->{objects}' @{$res;}->{'objects'}; -e syntax OK

        I suspect the ; after $res is the key but I'm not sure why. I shall have to give this some more thought.

        -- Ken

        which doesn't make sense.

        Sure it does, $res just happens to be a hash

Re: Referring to an array without copying to a separate variable first
by Anonymous Monk on Jun 27, 2013 at 00:08 UTC