Introduction to Perl Jarrad Battaglia
What I will be covering Foreach statements Hashes Splits
Hashes Hashes are very similar to arrays, but use strings instead of numbers for indexing Hashes use a key,value system Hash indices are called keys Say you create an array A(1..10) Hash(“one”,”1”,”two”,”2”) Hash{“one”} = “1” While Array [0] = 1
Reverse Hash Add new hash element Add multiple values to hash Format: $hash{“key”} = “value”; $hash{“one”} = “1”; Add multiple values to hash Format: %hash(“key1”, “value1”,”key2”, “value2”); %hash($key1 => $value1, $key2 => $value2) Reverse hash – so keys become values and values become keys %reverse_hash = reverse %hash;
Additional Hash Commands Delete one key-value from hash list delete $hash{key}; Delete all keys and values %hash = (); Check if key exists If(exists $hash{key}); Use variables in hash $hash{$key} = $value;
Hash to Array Hash to array Array to Hash %hash (“one”,”1”,”two”,”2”); @list = %hash List now has a size of 4 Array to Hash %hash = (); %hash = @list; Hash is now back to regular
Foreach statement Are used to iterate every value of an array or hash In an array the foreach statement will loop through every value of a list In a hash it will loop through the key, then go to its value, unless specified
Foreach examples Loop through hash with foreach Loop through a list foreach $hash (keys %hash) { print “keys\n”} Loop through a list foreach $list (@list) {print “$list\n” } foreach (@list) { print “$_\n” } Loop through numbers foreach (1..10) {print “$_\n”}
Foreach Example
Split Function The split function will split a scalar string into an array of strings For example @stringlist = split(/ /,"string into spaces"); foreach (@stringlist) { print “$_\n”; This would print “string”, “into”, “spaces” all on different lines
Split Examples Split two sentence into two Split input by spaces $string = “This is one. This is two” %splitstr = split(/\./,$string); Foreach(splitstr){print “$_\n”;} Split input by spaces $input = <STDIN>; foreach (split(“ “, $input)) { print “$_\n”;}
Hash Example