Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Cruel references

by uksza (Monsignor)
on Mar 06, 2005 at 00:16 UTC ( #436970=perlquestion: print w/ replies, xml ) Need Help??
uksza has asked for the wisdom of the Perl Monks concerning the following question:

Hello wise monks,

please, look at this sample code.
#!/usr/bin/perl use strict; use warnings; my %pets; my $color; $color="black"; $pets{$color}=\[]; push @${$pets{$color}},"cat"; push @${$pets{$color}},"dog"; $color="while"; $pets{$color}=\[]; push @${$pets{$color}},"rat"; push @${$pets{$color}},"bat"; foreach my $p (values %pets) { print "$p\n"; #^^^this is ref to ref to array? print "$$p\n"; #^^^this is ref to array print "@$$p\n\n"; #^^^this is array }
and output:
push @${$pets{$color}},"rat"; REF(0x815c4d0) ARRAY(0x815c4e8) rat bat REF(0x812ed0c) ARRAY(0x812ed48) cat dog
@$$p looks very strange.
why I can't use @$p.
why $p is ref to ref to array (or maybe is not?) not just ref to array?
I don't understand this. Could anybody help me?

stay in peace
Lukasz

Comment on Cruel references
Select or Download Code
Re: Cruel references
by japhy (Canon) on Mar 06, 2005 at 00:27 UTC
    It's because you have \[] instead of just []. [] is a reference to an anonymous array, and \[] is a reference TO a reference to an anonymous array.
    _____________________________________________________
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      of course!!
      Thanks a lot!
      This is right way:
      $pets{$color}=[]; push @{$pets{$color}},"cat";
Re: Cruel references
by trammell (Priest) on Mar 06, 2005 at 00:53 UTC
    You probably mean (or want):
    ... my %pets; my $color = 'black'; # $pets{$color} = []; # this line is unnecessary push @{ $pets{$color} }, 'cat'; push @{ $pets{$color} }, 'dog'; foreach my $p (values %pets) { print "@$p\n"; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2014-04-24 10:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (565 votes), past polls