Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Re: No: of values in a hashtable

by kcott (Chancellor)
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 examining the Monastery: (5)
As of 2018-02-17 20:24 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (249 votes). Check out past polls.