Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: length or array in a hash

by Cristoforo (Deacon)
on Nov 09, 2012 at 19:57 UTC ( #1003204=note: print w/replies, xml ) Need Help??

in reply to length or array in a hash

Your answer is here. Just look for the (second) listed type of variable, arrays.

Here is the bit you want to see (about arrays in scalar context).

You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don't bother. As it happens, using @array where Perl expects to find a scalar value ("in scalar context") will give you the number of elements in the array: 1. if (@animals < 5) { ... }
Here is your program using those features.
#!/usr/bin/perl use strict; use warnings; # the program my %hash = ( 'one' => [1], 'two' => [2,2], 'three' => [3,3,3], ); print "$hash{one}[0]\n"; print "$hash{two}[0]\n"; print "$hash{three}[0]\n"; while (my ($key, $aref) = each %hash) { # dereference array_reference # (and the @$aref array is in scalar context) printf "key=%s size=%d\n", $key, @$aref; }
1 2 3 key=three size=3 key=one size=1 key=two size=2

Replies are listed 'Best First'.
Re^2: length or array in a hash
by karlgoethebier (Parson) on Nov 10, 2012 at 16:39 UTC
    #!/usr/bin/perl + + use strict; use warnings; my %hash = ( one => [1], two => [ 2, 2 ], three => [ 3, 3, 3 ], ); for ( sort { $hash{$a} <=> $hash{$b} } keys %hash ) { print qq($_\t) . scalar( @{ $hash{$_} } ) . qq(\n); } print qq(\nVariatio delectat.\n);

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

      Thanks to all who replied and helped me out.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2017-01-17 15:06 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (157 votes). Check out past polls.