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

Thanks. However, that didn't quite get it. I made the above change and then tried the following:
foreach(keys $config->acls) { print "$_"; }
and
while(my ($name, $value) = each $config->acls()) { print "$name<br>$value<br>"; }
But both returned the error:
"Type of arg 1 to keys must be hash (not subroutine entry)"

Replies are listed 'Best First'.
Re^3: Hashes as return values
by g0n (Priest) on Jan 17, 2006 at 16:09 UTC
    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".