Home arrow Perl Programming arrow Page 2 - Hash Functions

Hash in Scalar Context - Perl

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

  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



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";

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- 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: