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).
When we discussed lists and arrays, we spent a lot of time talking about the difference between list and scalar context. Let’s look at what happens when we evaluate a hash in list context. This is demonstrated with the following program:
#!/usr/bin/perl -w # listcontext.pl
use strict;
my %person = ( name => 'John Doe', age => 39, phone => '555-1212', city => 'Chicago' );
This program takes the hash in list context in two ways. First, it assigns it to an array:
my @data = %person;
then the array is printed by joining its contents with the string “|” (more on thejoin()function in Chapter 7):
print "list context: ", join("|", @data), "\n";
The second way is to simply print it:
print "another way: ", %person, "\n";
Recall that all arguments to theprint()function are treated in list context.
When executed, we can see that a hash variable in list context is a list of the key/value pairs in the order stored in memory (not necessarily in the order in which the hash was created):
$ perl listcontext.pl list context: age|39|city|Chicago|phone|555-1212|name|John Doe another way: phone555-1212age39cityChicagonameJohn Doe $
We see a key (phone), followed by its value (555-1212), followed by a key (age), followed by its value (39), etc.