Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Referring to an array without copying to a separate variable first

by willjones (Sexton)
on Jun 26, 2013 at 21:52 UTC ( #1040851=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2020-04-10 00:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The most amusing oxymoron is:
















    Results (49 votes). Check out past polls.

    Notices?