in reply to length or array in a hash
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.
Prints:#!/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 (Abbot) on Nov 10, 2012 at 16:39 UTC | |
by ongaku (Initiate) on Nov 14, 2012 at 19:26 UTC |