In this second part of a two-part series on hashes in Perl, you'll learn about hash functions and hashes in different contexts. This article is excerpted from chapter five of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
A hash in scalar context is shown in this example:
#!/usr/bin/perl -w # scalarcontext.pl
use strict;
my %person = ( name => 'John Doe', age => 39, phone => '555-1212', city => 'Chicago' );
my $scalar = %person;
print "scalar context: $scalar\n";
if (%person) { print "%person has at least one key/value pair\n"; } else { print "%person is empty!\n"; }
Executing this program produces the following:
$ perl scalarcontext.pl scalar context: 3/8 %person has at least one key/value pair $
This code produces an unexpected result. The following code:
my $scalar = %person;
print "scalar context: $scalar\n";
prints the string “scalar context: 3/8”. Therefore, this hash in scalar context is “3/8” which means that we are using three buckets, or memory locations, out of eight buckets allocated.
This string is not so interesting unless we notice that the string “3/8” is a true value in Perl. Also, if our hash was empty, its value in scalar context would be the empty string, "". So a hash in scalar context is normally treated as a true/false value—true if there is anything in it, false if empty:
if (%person) { print "%person has at least one key/value pair\n"; } else { print "%person is empty!\n"; }