Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Perl Jarrad Battaglia.

Similar presentations


Presentation on theme: "Introduction to Perl Jarrad Battaglia."— Presentation transcript:

1 Introduction to Perl Jarrad Battaglia

2 What I will be covering Foreach statements Hashes Splits

3 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

4 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;

5 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;

6 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 Hash is now back to regular

7 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

8 Foreach examples Loop through hash with foreach Loop through a list
foreach $hash (keys %hash) { print “keys\n”} Loop through a list foreach $list {print “$list\n” } foreach { print “$_\n” } Loop through numbers foreach (1..10) {print “$_\n”}

9 Foreach Example

10 Split Function The split function will split a scalar string into an array of strings For example @stringlist = split(/ /,"string into spaces"); foreach { print “$_\n”; This would print “string”, “into”, “spaces” all on different lines

11 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”;}

12 Hash Example


Download ppt "Introduction to Perl Jarrad Battaglia."

Similar presentations


Ads by Google