Hashes

16
Perl Programming Perl Programming Course Course Hashes Hashes Krassimir Berov I-can.eu

description

This is the fourth set of slightly updated slides from a Perl programming course that I held some years ago. I want to share it with everyone looking for intransitive Perl-knowledge. A table of content for all presentations can be found at i-can.eu. The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse

Transcript of Hashes

Page 1: Hashes

Perl Programming Perl Programming CourseCourse

HashesHashes

Krassimir Berov

I-can.eu

Page 2: Hashes

HashesHashes

Page 3: Hashes

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

Page 4: Hashes

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 key The keys of a hash are not pre-declared. If the key does not exist during an ASSIGNMENT, the key is does 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 (%) followed A 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",););

Page 5: Hashes

Hash representationHash representation

• There is not really a literal representation for a There 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 and Each pair of elements in the list defines a key and its corresponding value. This representation can its corresponding value. This representation can be assigned into another hash, which will then be assigned into another hash, which will then recreate the same hash. recreate the same hash.

• Example:Example:use Data::Dumper; $\ =$/;use Data::Dumper; $\ =$/;my my %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 pairprint Dumper(\%fruit_colors);print Dumper(\%fruit_colors);

Page 6: Hashes

Working with hash elementsWorking with hash elements

• existsexists

• defineddefined

• deletedelete

Page 7: Hashes

Working with hash elementsWorking with hash elements

• exists EXPRexists EXPRGiven an expression that specifies a hash element Given an expression that specifies a hash element or array element, returns true if the specified or array element, returns true if the specified element in the hash or array has ever been element in the hash or array has ever been initialized, even if the corresponding value is initialized, 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]};

Page 8: Hashes

Working with hash elementsWorking with hash elements

• defined EXPRdefined EXPR• Returns a Boolean value telling whether EXPR has a value Returns a Boolean value telling whether EXPR has a value

other than the undefined value other than the undefined value undefundef......

• When used on a hash element, it tells you whether the When 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. Use Use 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'};#...#...

Page 9: Hashes

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 the array 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 as Returns a list with the same number of elements as the number of elements for which deletion was the number of elements for which deletion was attempted. Each element of that list consists of either attempted. Each element of that list consists of either the value of the element deleted, or the undefined the value of the element deleted, or the undefined value. value.

• In scalar context, returns the value of the last In scalar context, returns the value of the last element deleted (or the undefined value if that element deleted (or the undefined value if that element did not exist).element did not exist).See: perlfunc/deleteSee: perlfunc/delete

Page 10: Hashes

Working with hash elementsWorking with hash elements

• delete (Example)delete (Example)

my %f_colors = ('apple', 'red', 'banana', 'yellow');my %f_colors = ('apple', 'red', 'banana', 'yellow');my @f_colors = %f_colors;my @f_colors = %f_colors;push @f_colors,('pear','yellow');push @f_colors,('pear','yellow');%f_colors = @f_colors;%f_colors = @f_colors;print Dumper \@f_colors;print Dumper \@f_colors;print Dumper \%f_colors;print Dumper \%f_colors;print delete $f_colors[-1];print delete $f_colors[-1];print delete @f_colors{qw(apple banana)};print delete @f_colors{qw(apple banana)};print 'after delete:';print 'after delete:';print Dumper \%f_colors;print Dumper \%f_colors;print Dumper \@f_colors;print Dumper \@f_colors;

Page 11: Hashes

Other Hash FunctionsOther Hash Functions

• eacheach

• keyskeys

• valuesvalues

Page 12: Hashes

Other Hash FunctionsOther Hash Functions

• each HASHeach HASH• When called in list context, returns a 2-element list When called in list context, returns a 2-element list

consisting of the key and value for the next element of a consisting 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 the When 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 same The actual random order is guaranteed to be in the same order as either the order as either the keyskeys or or valuesvalues function would function 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=>$value\n";print "$key=>$value\n";}}

Page 13: Hashes

Other Hash FunctionsOther Hash Functions

• keys HASHkeys HASHReturns a list consisting of all the keys of Returns 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 keyforeach $key (sort(keys %ENV)) {foreach $key (sort(keys %ENV)) { print $key, ' => ', $ENV{$key}, "\n";print $key, ' => ', $ENV{$key}, "\n";}}

Page 14: Hashes

Other Hash FunctionsOther Hash Functions

• values HASHvalues HASH

• Returns a list consisting of all the values of the Returns a list consisting of all the values of the named hash. (In a scalar context, returns the named hash. (In a scalar context, returns the number of values.)number of values.)

• There is a single iterator for each hash, shared There is a single iterator for each hash, shared by all by all eacheach, , keyskeys, and , and valuesvalues function calls in function calls in the program.the program.

#sorted by value#sorted by valueforeach my $value (sort(values %ENV)) {foreach my $value (sort(values %ENV)) { print $value, "\n";print $value, "\n";}}

Page 15: Hashes

HashesHashes

Questions?Questions?

Page 16: Hashes

ExercisesExercises