Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^3: Hashes as return values

by g0n (Priest)
on Jan 17, 2006 at 16:09 UTC ( [id://523764]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Hashes as return values
in thread Hashes as return values

The error means exactly what it says, 'keys' needs a hash, not a hashref, or anything else. This works:

use strict; use warnings; my $obj = Foo->new(); for my $key (keys %{$obj->{acls}}) { print "$key\n"; } package Foo; sub new { my $self = shift; my %obj = ( acls => { a=>1, b=>2 } ); return bless \%obj; }

Note the %{} round $obj->{acls} dereferencing the hashref into a hash.

Update: Just as added clarification, since you were talking about return values from functions:

use strict; use warnings; my $obj = Foo->new(); for my $key (keys %{$obj->{acls}}) { print "$key\n"; } for my $key (keys %{$obj->acls}) { print "$key\n"; } package Foo; sub new { my $self = shift; my %obj = ( acls => { a=>1, b=>2 } ); return bless \%obj; } sub acls { my $self = shift; return \%{$self->{acls}}; }

The second for loop calls acls() to get at the content of the attribute {acls}, dereferences it, and iterates through printing the keys. The first loop is accessing the hashref directly, rather than through a function call.

--------------------------------------------------------------

"If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."

John Brunner, "The Shockwave Rider".

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-23 06:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found