Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: No: of values in a hashtable

by kcott (Abbot)
on Sep 18, 2012 at 06:15 UTC ( #994188=note: print w/ replies, xml ) Need Help??


in reply to No: of values in a hashtable

From perldata:
"If you evaluate an array in scalar context, it returns the length of the array."
From scalar:
"Forces EXPR to be interpreted in scalar context ..."

Accordingly, scalar @{ $weekly_hash{$i} } will return the number of values:

$ perl -Mstrict -Mwarnings -E ' my %weekly_hash; my $i = 1; push @{ $weekly_hash{$i} },"mon","ret","tue","retik","wed","true"; say scalar @{ $weekly_hash{$i} }; ' 6

Your code shows no undefined values. Your text has "... the number of values ...". An undefined value is still a value:

$ perl -Mstrict -Mwarnings -E ' my %weekly_hash; my $i = 1; push @{ $weekly_hash{$i} },"mon","ret","tue","retik","wed","true", und +ef; say scalar @{ $weekly_hash{$i} }; ' 7

If you really meant that you only wanted a count of defined values, you can do this:

$ perl -Mstrict -Mwarnings -E ' my %weekly_hash; my $i = 1; push @{ $weekly_hash{$i} },"mon","ret","tue","retik","wed","true", und +ef; say scalar @{[ grep { defined } @{ $weekly_hash{$i} } ]}; ' 6

The count of elements in an array is always available via scalar; there's no need to introduce temporary count variables.

-- Ken


Comment on Re: No: of values in a hashtable
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (9)
As of 2014-12-19 12:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (81 votes), past polls