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

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; }
Prints:
1 2 3 key=three size=3 key=one size=1 key=two size=2


Comment on Re: length or array in a hash
Select or Download Code
Re^2: length or array in a hash
by karlgoethebier (Curate) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2014-08-29 17:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (284 votes), past polls