Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: No: of values in a hashtable

by kcott (Canon)
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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://994188]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2017-02-25 21:09 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (368 votes). Check out past polls.