Home arrow Perl Programming arrow Hash Functions

Hash Functions

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).

TABLE OF CONTENTS:
  1. Hash Functions
  2. Hash in Scalar Context
  3. Hash Functions
  4. Hash Examples
  5. Counting Things
By: Apress Publishing
Rating: starstarstarstarstar / 1
May 06, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Hash in List Context

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'
);

my @data = %person;

print "list context: ", join("|", @data), "\n";
print "another way: ", %person, "\n";

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.



 
 
>>> More Perl Programming Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PERL PROGRAMMING ARTICLES

- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: