For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > July 2006 > empty hash ref detection









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author empty hash ref detection
KenPerl@gmail.com

2006-07-24, 7:56 am

based on my understanding, to check if a hash ref is empty or not, I
can use code like this,

if (keys %$hashref) {
# it is not empty
}
else {
# it is a empty hash
}

but below debugging code doesn't work, could someone show me a light?

DB<27> p Dumper($people)
$VAR1 = {
'name' => 'Sular',
'comment' => {},
};

DB<34> p keys %$people->{"comment"}
Type of arg 1 to keys must be hash (not hash element)

Paul Lalli

2006-07-24, 7:56 am


KenPerl@gmail.com wrote:
> based on my understanding, to check if a hash ref is empty or not, I
> can use code like this,
>
> if (keys %$hashref) {
> # it is not empty
> }
> else {
> # it is a empty hash
> }


This is all correct.

> but below debugging code doesn't work, could someone show me a light?
>
> DB<27> p Dumper($people)
> $VAR1 = {
> 'name' => 'Sular',
> 'comment' => {},
> };
>
> DB<34> p keys %$people->{"comment"}


This, however is not. The reason is that the actual rule for
dereferencing a hash reference is to first surround the reference with
curly braces, and *then* to prepend the percent sign. You are only
permitted to omit the first step if the reference is contained in a
simple scalar variable (like $hashref above). Here, your reference is
not in a scalar variable - it is the value of a hash. Therefore, you
must include the { }, like so:

keys %{$people->{comment}}

Please make sure you read:
perldoc perlreftut
perldoc perllol
perldoc perldsc

Paul Lalli

KenPerl@gmail.com

2006-07-24, 9:56 pm

Thanks Paul, your reply is very useful and thanks once more.
Paul Lalli wrote:
> KenPerl@gmail.com wrote:
>
> This is all correct.
>
>
> This, however is not. The reason is that the actual rule for
> dereferencing a hash reference is to first surround the reference with
> curly braces, and *then* to prepend the percent sign. You are only
> permitted to omit the first step if the reference is contained in a
> simple scalar variable (like $hashref above). Here, your reference is
> not in a scalar variable - it is the value of a hash. Therefore, you
> must include the { }, like so:
>
> keys %{$people->{comment}}
>
> Please make sure you read:
> perldoc perlreftut
> perldoc perllol
> perldoc perldsc
>
> Paul Lalli


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com