This document provides an overview of hashes in Perl programming. It defines a hash as a set of key-value pairs where keys are not pre-declared and can be created during assignment. Functions for working with hash elements include exists(), defined(), and delete(). Other hash functions include each() to iterate over elements, keys() to return a list of all keys, and values() to return a list of all values.
3. ContentsContents
1.1. What is a hash?What is a hash?
2.2. Hash representationHash representation
3.3. Working with hash elements (exists,Working with hash elements (exists,
delete, defined)delete, defined)
4.4. Other Hash FunctionsOther Hash Functions
4. What is a hash?What is a hash?
• A hash represents a set of key/value pairsA hash represents a set of key/value pairs
• The keys of a hash are not pre-declared. If the keyThe keys of a hash are not pre-declared. If the key
does not exist during an ASSIGNMENT, the key isdoes not exist during an ASSIGNMENT, the key is
created and given the assigned value.created and given the assigned value.
• A hash variable name is a percent sign (%) followedA hash variable name is a percent sign (%) followed
by a letter, followed by zero or more letters, digits,by a letter, followed by zero or more letters, digits,
and underscoresand underscores
my %fruit_colors = (my %fruit_colors = (
apple => "red",apple => "red",
banana => "yellow",banana => "yellow",
););
5. Hash representationHash representation
• There is not really a literal representation for aThere is not really a literal representation for a
hash, so instead hash is represented as a list.hash, so instead hash is represented as a list.
• Each pair of elements in the list defines a key andEach pair of elements in the list defines a key and
its corresponding value. This representation canits corresponding value. This representation can
be assigned into another hash, which will thenbe assigned into another hash, which will then
recreate the same hash.recreate the same hash.
• Example:Example:
use Data::Dumper; $ =$/;use Data::Dumper; $ =$/;
mymy %fruit_colors%fruit_colors == ('apple', 'red', 'banana', 'yellow')('apple', 'red', 'banana', 'yellow');;
print Dumper(%fruit_colors);print Dumper(%fruit_colors);
my @fruit_colors = %fruit_colors;my @fruit_colors = %fruit_colors;
print Dumper(@fruit_colors);print Dumper(@fruit_colors);
%fruit_colors = @fruit_colors;%fruit_colors = @fruit_colors;
$fruit_colors{pear} = 'yellow';#add a key/value pair$fruit_colors{pear} = 'yellow';#add a key/value pair
print Dumper(%fruit_colors);print Dumper(%fruit_colors);
6. Working with hash elementsWorking with hash elements
• existsexists
• defineddefined
• deletedelete
7. Working with hash elementsWorking with hash elements
• exists EXPRexists EXPR
Given an expression that specifies a hash elementGiven an expression that specifies a hash element
or array element, returns true if the specifiedor array element, returns true if the specified
element in the hash or array has ever beenelement in the hash or array has ever been
initialized, even if the corresponding value isinitialized, even if the corresponding value is
undefined.undefined.
The element is not autovivified if it doesn't exist.The element is not autovivified if it doesn't exist.
my %f_colors = ('apple', 'red', 'banana', 'yellow');my %f_colors = ('apple', 'red', 'banana', 'yellow');
my @f_colors = %f_colors;my @f_colors = %f_colors;
exists $f_colors[0] andexists $f_colors[0] and
print $f_colors[0] .' exists';print $f_colors[0] .' exists';
exists $f_colors{'apple'} andexists $f_colors{'apple'} and
print ' and is '.$f_colors{'apple'};print ' and is '.$f_colors{'apple'};
print 'Ops... 'print 'Ops... '
.$f_colors[0].' is '.$f_colors{$f_colors[0]};.$f_colors[0].' is '.$f_colors{$f_colors[0]};
8. Working with hash elementsWorking with hash elements
• defined EXPRdefined EXPR
• Returns a Boolean value telling whether EXPR has a valueReturns a Boolean value telling whether EXPR has a value
other than the undefined valueother than the undefined value undefundef......
• When used on a hash element, it tells you whether theWhen used on a hash element, it tells you whether the
value is defined, not whether the key exists in the hash.value is defined, not whether the key exists in the hash.
UseUse existsexists for the latter purpose.for the latter purpose.
my %f_colors = ('apple', 'red', 'banana', 'yellow');my %f_colors = ('apple', 'red', 'banana', 'yellow');
my @f_colors = %f_colors;my @f_colors = %f_colors;
defined $f_colors[0] anddefined $f_colors[0] and
print $f_colors[0] .' defined';print $f_colors[0] .' defined';
defined $f_colors{'apple'} anddefined $f_colors{'apple'} and
print ' and is '.$f_colors{'apple'};print ' and is '.$f_colors{'apple'};
#...#...
9. Working with hash elementsWorking with hash elements
• delete EXPRdelete EXPR
• Given an expression that specifies a hash element,Given an expression that specifies a hash element,
array element, hash slice, or array slice, deletes thearray element, hash slice, or array slice, deletes the
specified element(s) from the hash or array...specified element(s) from the hash or array...
• Returns a list with the same number of elements asReturns a list with the same number of elements as
the number of elements for which deletion wasthe number of elements for which deletion was
attempted. Each element of that list consists of eitherattempted. Each element of that list consists of either
the value of the element deleted, or the undefinedthe value of the element deleted, or the undefined
value.value.
• In scalar context, returns the value of the lastIn scalar context, returns the value of the last
element deleted (or the undefined value if thatelement deleted (or the undefined value if that
element did not exist).element did not exist).
See: perlfunc/deleteSee: perlfunc/delete
12. Other Hash FunctionsOther Hash Functions
• each HASHeach HASH
• When called in list context, returns a 2-element listWhen called in list context, returns a 2-element list
consisting of the key and value for the next element of aconsisting of the key and value for the next element of a
hash, so that you can iterate over it.hash, so that you can iterate over it.
• When called in scalar context, returns only the key for theWhen called in scalar context, returns only the key for the
next element in the hash.next element in the hash.
• Entries are returned in an apparently random order.Entries are returned in an apparently random order.
• The actual random order is guaranteed to be in the sameThe actual random order is guaranteed to be in the same
order as either theorder as either the keyskeys oror valuesvalues function wouldfunction would
produce on the same (unmodified) hash.produce on the same (unmodified) hash.
while (($key,$value) = each %ENV) {while (($key,$value) = each %ENV) {
print "$key=>$valuen";print "$key=>$valuen";
}}
13. Other Hash FunctionsOther Hash Functions
• keys HASHkeys HASH
Returns a list consisting of all the keys ofReturns a list consisting of all the keys of
the named hash. (In scalar context,the named hash. (In scalar context,
returns the number of keys.)returns the number of keys.)
#sorted by key#sorted by key
foreach $key (sort(keys %ENV)) {foreach $key (sort(keys %ENV)) {
print $key, ' => ', $ENV{$key}, "n";print $key, ' => ', $ENV{$key}, "n";
}}
14. Other Hash FunctionsOther Hash Functions
• values HASHvalues HASH
• Returns a list consisting of all the values of theReturns a list consisting of all the values of the
named hash. (In a scalar context, returns thenamed hash. (In a scalar context, returns the
number of values.)number of values.)
• There is a single iterator for each hash, sharedThere is a single iterator for each hash, shared
by allby all eacheach,, keyskeys, and, and valuesvalues function calls infunction calls in
the program.the program.
#sorted by value#sorted by value
foreach my $value (sort(values %ENV)) {foreach my $value (sort(values %ENV)) {
print $value, "n";print $value, "n";
}}