Broad Network


Perl Hash Predefined Functions

Using Perl Hashes Part 1

Perl Course

Foreword: In this part of the series, I talk about the functions: keys(), values(), delete(), undef(), exists(), defined(), each(), and the hash slice operation; in that order.

By: Chrysanthus Date Published: 3 Nov 2015

Introduction

This is part 1 of my series, Using Perl Hashes. In this part of the series, I talk about the functions: keys(), values(), delete(), undef(), exists(), defined(), each(), and the hash slice operation; in that order.

Pre-Knowledge
This series is part of the volume, Perl Course. At the bottom of this page, you have links to the different series you should have read before coming here.

A Hash Example
The obvious way to define a hash is in the example:

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

Note that as no value was given for Pineapple, Perl gave it the value of undef, unknown to you. This definition could still have been written as follows:

    my %fruitColor;

    $fruitColor{Apple} = "purple";
    $fruitColor{Banana} = "yellow";
    $fruitColor{Pear} = "green";
    $fruitColor{Lemon} = "green";
    $fruitColor{Pineapple};

Here, again, no value has been given for Pineapple, so Perl has given it the value of undef.

The keys Function
The syntax of the keys function is:

    keys (%hashName)

It returns a list (which can be held by an array) of all keys in the hash. Try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    my @arr = keys (%fruitColor);

    print "$_ " foreach @arr;

The output is:

    Pear Banana Apple Lemon Pineapple

The order of the return keys is not predetermined (not necessarily the way they were typed into the hash).

The values Function
The syntax for the values function is:

    values(%hashName)

The values function behaves in a similar way to the keys function except that it returns a list of the values in the hash and not a list of the keys. Read and try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    my @arr = values(%fruitColor);
    print @arr;

Again the order of the returned values is not predetermined.

The delete Function
This function deletes both the key and the value of the key/value pair. The syntax is:

    delete EXPR

EXPR can be referring to a key e.g. $fruitColor{Banana}or to a hash slice (see below). In any case, at least one value of the key/value pairs(s) is returned by EXP, but the element (key/value pair) is/are deleted completely. The rest of the hash remains, but lacking at least one element (deleted).

In list context the delete() function returns the values of the elements deleted. In scalar context, it returns the last value of the key/value pair deleted. Read and try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    my @arr = delete($fruitColor{Banana});

    print @arr, "\n";
    print %fruitColor, "\n";

The output is:

    yellow
    PineapplePeargreenLemongreenApplepurple

Note: setting (assigning) the value of a key/value pair to undef, does not remove the element. You end up with a new key/value pair, whose value is undef. undef means nothing. This does not remove the key, and so does not remove the element. However, delete() removes both the key and the value, which may be undef. So delete() removes the element.

The undef() function
Assigning undef to the element as in,

    $fruitColor{Pineaple} = undef;

or

    undef($fruitColor{Banana})

does not really remove the key/value pair from the hash. It makes the value of the key/value pair undefined (nothing), and not the element (key/value pair). You cannot really use undef() to remove the key/value pair from a hash. That simply replaces the value of the key/value pair with undef. However, you can use undef() to remove the whole hash list from the hash variable. Read and try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    undef(%fruitColor);

    print %fruitColor;

The output is nothing, showing that all the hash content (list) has been removed (deleted).

The exists() Function
If an element (key/value pair) in a hash exists, it means the key of the element has the value, undef or something else. The exists() function checks whether an element exists by checking if the corresponding key exists. It returns true for existence and false for non-existence. If the value of the key is undef, exists() will still return true. Both key/value pair should not exist, for exists() to return false. The exists() function on a deleted element or element that was never there, returns false. The exists() function on an undefined element (key present but value is undef) returns true. The syntax for the exists() function is,

    exists EXPR

where EXPR is $hash{$key}

Try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    delete($fruitColor{Banana});

    if (exists($fruitColor{Banana}))
        {
            print "Element with key, Banana exists.";
        }
    else
        {
            print "Element with key, Banana does NOT exist.";
        }

The output is:

    Element with key, Banana does NOT exist.

since it was deleted.

The defined Function
The defined() function tests whether a function or variable has (is assigned) the undef value. It can also test whether a value is undef or not. Using the defined() function with hashes, can give wrong results. Do not use it with hashes.

To test whether an element (key/value pair) of a hash exists, use the exists() function. To test whether the value of an existing key is undef or not, use a Boolean condition. Recall, undef means false. To test whether a hash is empty, use a Boolean condition. An empty hash is equivalent to undef or () assigned to the hash variable. Both undef and () is equivalent to false. Read and try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    if ($fruitColor{Pineapple})
        {
            print "Pineapple key has a value that is not undef.\n";
        }
    else
        {
            print "The value of pineapple key is undef.\n";
        }

    %fruitColor = ();

    if (%fruitColor)
        {
            print "The hash is not empty or the assigned value is undef.\n";
        }
    else
        {
            print "The assigned value to the hash is equivalent to undef or ().\n";
        }

The output is:

    The value of pineapple key is undef.
    The assigned value to the hash is equivalent to undef or ().

In the first if-condition, $fruitColor{Pineapple} results in undef, which is false. In the second if-condition, %fruitColor results in (), which is false.

The each Function
The syntax to use the each function is:

    each (%HashName)

This expression returns either the next key/value pair or the next key, depending on whether we are dealing with the list context (receiving variable is an array) or scalar context (receiving variable is a scalar). In the code below, it is the next key/value pair that will be returned. In the code below, I use the hash above with five elements. So if you use the each function five times, you will have the five different key/value pairs. Read and try the code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    print each (%fruitColor); print "\n";
    print each (%fruitColor); print "\n";
    print each (%fruitColor); print "\n";
    print each (%fruitColor); print "\n";
    print each (%fruitColor); print "\n";

In my computer I had the following output:

Bananayellow
Pineapple
Applepurple
Lemongreen
Peargreen

The order of the key/value pairs is not necessarily the same order in which we typed them into the hash. Recall that this order cannot be predetermined. So the each function will return the next key/value pair but not necessarily in the original order. It begins with what it considers as the first, then if it is called again, it returns what it considers as the next, and so on. The value for the pineapple key is undef, and it is not printed. The above code can be coded in a while loop in list context, as follows:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    while ((my $key, my $value) = each %fruitColor)
        {
         print "$key $value \n";
        }

I tried the code in my computer and the output was:

    Pear green
    Pineapple
    Banana yellow
    Apple purple
    Lemon green

In the while-condition, the return key/value pair of the each() function is received by a list of two variables (my $key, my $value). Now, a non-empty list is equivalent to true, and so the block of the loop is evaluated.

In scalar context, a similar while loop is:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    while (my $key = each %fruitColor)
        {
         print "$key \n";
        }

I tried the code in my computer and I had,

    Pear
    Lemon
    Banana
    Apple
    Pineapple

Hash Slice
A hash slice is a kind of array variable. However, instead of having square brackets, you have curly brackets; instead of having indices (numbers) within the curly brackets, you have keys in quotes. Read and try the following code:

use strict;

    my %fruitColor = (Apple => "purple", Banana => "yellow", Pear => "green", Lemon => "green", Pineapple =>);

    print @fruitColor{"Apple", "Banana", "Lemon"};

The output is:

    purpleyellowgreen

That is, purple for Apple, yellow for Banana and green for lemon. You can replace the content of the curly brackets with an array, e.g. @arr.

That is it for this part of the series. We stop here and continue in the next part.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

NEXT

Comments

Become the Writer's Fan
Send the Writer a Message