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

Cruel references

by uksza (Abbot)
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

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://436970]
Approved by friedo
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2017-11-24 14:48 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (349 votes). Check out past polls.