90 likes | 106 Views
Learn about Perl hashes and foreach control structures. Understand the difference between arrays and hashes, how to declare and manipulate hash indexes, and use the foreach loop for efficient iterations. Dive into examples and functions like the split function, and access additional references for in-depth learning.
E N D
An Introduction to Perl – Part II By: Christopher Todd
Hashes • Hashes are variables that hold lists. • Arrays are also variables that hold lists, but the fundamental difference is how that lists are indexed. • Arrays use numbers for indexing • Hashes use strings for indexing • In a hash, you must declare the index with the variable. There is no range operator for hashes. • Indexes in a Hash are known as “Keys”
Examples of Hashes • To define a Hash, we place a ‘%’ before the name of the Hash. • Ex. If we wish to make a hash named ‘Example’, we declare %Example. • We must also declare the index when we declare the variable. • Ex. We wish to make a hash combining the month name (index/key) and number (data): • %Month (“January”, 1, “February”, 2,…, “December”, 12)
Inversing a Hash • Because a Hash’s indexes and data are both assignable, we can take data from the indexes and switch it with the data. • As in the example before, we can switch the %Month hash so that the indexes are the number representing the month and the names are the data. • %Month_Numbers = reverse %Month
Foreach Control Structure • The Foreach Control Structure is a form of a loop • The loop will go through a array or list, executing one iteration for every value of the list. • The list one at a time until the list is exhausted
Example of a Foreach Command Ex. foreach (1..10) { print " $_\n"; } The command above will go through the list of 1-10 until the list is done. The example above will print the list 1-10, with each number on a separate line.
Split Functions • Split is a function that is used to separate data. • A split can be created using a letter, number, symbol, or any character that can be part of a string. • The split function can be used to break a function into parts and insert them into a list or an array.
Example of a Split Function Ex. $Example_String = “This is an example of a split function”; @Example_Array = split “ “, $Example_String; In the Example above, we make a string, and then split the string into an array. Every space in the string serves a a split to the string and part of the string is inserted into the array.
References • “Perl Basics” • http://www.cs.drexel.edu/~knowak/cs265_fall_2009/perl_basics.pdf • “Introduction to Perl” • http://www.tizag.com/perlT/index.php • “How To Perl” • http://www.perlmeme.org/ • “Perl Tutorial” • http://www.comp.leeds.ac.uk/Perl/