Hash Tools

Hash Tools

Hash Functions

What

    delete $hash{$key}      # deletes the specified key/value pair,
                            # and returns the deleted value
    
    exists $hash{$key}      # returns true if the specified key exists
                            # in the hash.
    
    keys %hash              # returns a list of keys for that hash
    
    values %hash            # returns a list of values for that hash
    
    scalar %hash            # returns true if the hash has elements
                            # defined (e.g. it's not an empty hash)

Hashes

A hash is a special kind of array – an associative array, or paired group of elements. Perl hash names are prefixed with a percent sign (%), and consist of pairs of elements – a key and a data value. Here’s how to define a hash:

Hash Name key value

[cc lang="perl"]
%pages = ( “fred”, “http://www.cgi101.com/~fred/”,
“beth”, “http://www.cgi101.com/~beth/”,
“john”, “http://www.cgi101.com/~john/” );
[/cc]
Another way to define a hash would be as follows:

%pages = ( fred => “http://www.cgi101.com/~fred/”,
beth => “http://www.cgi101.com/~beth/”,
john => “http://www.cgi101.com/~john/” );

The => operator is a synonym for “, “. It also automatically quotes the left side of the argument, so enclosing quotes are not needed.

This hash consists of a person’s name for the key, and their URL as the data element. You refer to the individual elements of the hash with a $ sign (just like you did with arrays), like so:

$pages{‘fred’}

In this case, “fred” is the key, and $pages{‘fred’} is the value associated with that key – in this case, it would be “http://www.cgi101.com/~fred/”.

If you want to print out all the values in a hash, you’ll need a foreach loop, like follows:

foreach $key (keys %pages) {
print “$key’s page: $pages{$key}\n”;
}

This example uses the keys function, which returns an array consisting only of the keys of the named hash. One drawback is that keys %hashname will return the keys in random order – in this example, keys %pages could return (“fred”, “beth”, “john”) or (“beth”, “fred”, “john”) or any combination of the three. If you want to print out the hash in exact order, you have to specify the keys in the foreach loop:

foreach $key (“fred”,”beth”,”john”) {
print “$key’s page: $pages{$key}\n”;
}

Data Source from www.cgi101.com

About the Author

Programmer