SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
Perl ProgrammingPerl Programming
CourseCourse
HashesHashes
Krassimir Berov
I-can.eu
HashesHashes
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
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",
););
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);
Working with hash elementsWorking with hash elements
• existsexists
• defineddefined
• deletedelete
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]};
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'};
#...#...
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
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;
Other Hash FunctionsOther Hash Functions
• eacheach
• keyskeys
• valuesvalues
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";
}}
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";
}}
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";
}}
HashesHashes
Questions?Questions?
ExercisesExercises

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
String variable in php
String variable in phpString variable in php
String variable in php
chantholnet
 
Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
rhshriva
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
Utkarsh Sengar
 

Was ist angesagt? (20)

Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
Perl
PerlPerl
Perl
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
String variable in php
String variable in phpString variable in php
String variable in php
 
Bioinformatics p2-p3-perl-regexes v2014
Bioinformatics p2-p3-perl-regexes v2014Bioinformatics p2-p3-perl-regexes v2014
Bioinformatics p2-p3-perl-regexes v2014
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
Scripting3
Scripting3Scripting3
Scripting3
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
 

Andere mochten auch

Perl. Od podstaw
Perl. Od podstawPerl. Od podstaw
Perl. Od podstaw
Wydawnictwo Helion
 
Things I Learned From Having Users
Things I Learned From Having UsersThings I Learned From Having Users
Things I Learned From Having Users
Dave Cross
 

Andere mochten auch (8)

Perl. Od podstaw
Perl. Od podstawPerl. Od podstaw
Perl. Od podstaw
 
Modern Perl for the Unfrozen Paleolithic Perl Programmer
Modern Perl for the Unfrozen Paleolithic Perl ProgrammerModern Perl for the Unfrozen Paleolithic Perl Programmer
Modern Perl for the Unfrozen Paleolithic Perl Programmer
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Things I Learned From Having Users
Things I Learned From Having UsersThings I Learned From Having Users
Things I Learned From Having Users
 
Moo the universe and everything
Moo the universe and everythingMoo the universe and everything
Moo the universe and everything
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Future of PERL in IT
Future of PERL in ITFuture of PERL in IT
Future of PERL in IT
 
Modern Perl Catch-Up
Modern Perl Catch-UpModern Perl Catch-Up
Modern Perl Catch-Up
 

Ähnlich wie Hashes

Ähnlich wie Hashes (20)

Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Marcs (bio)perl course
Marcs (bio)perl courseMarcs (bio)perl course
Marcs (bio)perl course
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16
 
Migrating to Puppet 4.0
Migrating to Puppet 4.0Migrating to Puppet 4.0
Migrating to Puppet 4.0
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 
Php Chapter 2 3 Training
Php Chapter 2 3 TrainingPhp Chapter 2 3 Training
Php Chapter 2 3 Training
 
PHP-Overview.ppt
PHP-Overview.pptPHP-Overview.ppt
PHP-Overview.ppt
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 

Mehr von Krasimir Berov (Красимир Беров)

Mehr von Krasimir Berov (Красимир Беров) (9)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Network programming
Network programmingNetwork programming
Network programming
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Syntax
SyntaxSyntax
Syntax
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 

Hashes

  • 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
  • 10. 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;
  • 11. Other Hash FunctionsOther Hash Functions • eacheach • keyskeys • valuesvalues
  • 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"; }}