Presentation is loading. Please wait.

Presentation is loading. Please wait.

Perl Day 5. Arrays vs Hash Arrays are one way to store multiple things in a variable. Hashes are another. Arrays are one way to store multiple things.

Similar presentations


Presentation on theme: "Perl Day 5. Arrays vs Hash Arrays are one way to store multiple things in a variable. Hashes are another. Arrays are one way to store multiple things."— Presentation transcript:

1 Perl Day 5

2 Arrays vs Hash Arrays are one way to store multiple things in a variable. Hashes are another. Arrays are one way to store multiple things in a variable. Hashes are another. –In an array, the elements in the array are automatically numbered, 0, 1, 2, 3…. –In a hash, you can decide what they are called –Hashes start with a % instead of a @ –You use => to indicate what belongs to what. –When you want to pull the answer back you use $hash{key} %FruitColors=( 'apple' => 'green', 'banana' => 'yellow', 'orange' => 'orange'); print("Apples are $FruitColors{apple}\n");

3 Keys Each array element is said to have a “key” and a “value”. Each array element is said to have a “key” and a “value”. –In the previous example, the fruit name (apple, banana etc) are keys. The colors are “values”. –You can get the list of “keys” in a hash with the keys command. It returns an array: @Fruits=keys %FruitColors; –You can also use a loop show all of them: foreach $Fruit (keys %FruitColors) { print(“$Fruit is $FruitColors{$Fruit}\n”); print(“$Fruit is $FruitColors{$Fruit}\n”);}

4 sort Sometimes you want your fruits alphabetized: Sometimes you want your fruits alphabetized: The fruits in order are: The fruits in order are: foreach $Fruit (sort keys %FruitColors) { print(“$Fruit is $FruitColors{$Fruit}\n”); print(“$Fruit is $FruitColors{$Fruit}\n”);}

5 Uses for Hashes Lets imagine you had of the first name of everyone in our office. You might want to know how many people named “Michael” we have. Lets imagine you had of the first name of everyone in our office. You might want to know how many people named “Michael” we have. All Hash values start off as 0, so you can simply add 1 to them each time you find a Michael All Hash values start off as 0, so you can simply add 1 to them each time you find a Michael @FirstNames=(‘michael’,’adam’,’enda’,’lucas’,’fay’,’michael’,’michael’,’sp encer’,’kris’); foreach $Name (@FirstNames) { $NameCount{$Name}++; $NameCount{$Name}++;} foreach $FirstName (keys %NameCount) { print(“There are $NameCount{$FirstName} people named $FirstName\n”); print(“There are $NameCount{$FirstName} people named $FirstName\n”);}

6 Removing something from a hash If you need to get rid of something out of a hash, you use delete If you need to get rid of something out of a hash, you use deletedelete($FruitColor{banana});

7 Abstraction One of the most important concepts in doing a big task is Abstraction. One of the most important concepts in doing a big task is Abstraction. –Imagine I told you to build this building. How would you do it? 1.Hire an architect 2.Buy some land 3.Hire a contractor to oversee building it –Note the details of how the contractor hires his people etc are not important right now.  This is abstraction, solving smaller problems, which will ultimately allow you to solve the bigger problem.

8 Abstraction in programming Likewise when asked to write a big script, you don’t just try to do it all at once. Likewise when asked to write a big script, you don’t just try to do it all at once. –Do all the little parts you know how to do first –Use those building blocks to solve the bigger problem –Examples of how to break things up  Dealing with @ARGV  Opening a file and reading it’s contents, putting them into an array  Doing some regular expression magic to figure something out  Writing out the result to a file. –There is no single right answer on how things should be broken up, but a good rule of thumb is if you can’t explain in 1 sentence what something it doing, it should be broken up into smaller tasks.

9 Sub tasks In perl each sub task is called a subroutine (sub for short) In perl each sub task is called a subroutine (sub for short) –Each has a name, you should call it something descriptive –Subroutines can be used over an over (that’s the whole point)  Each time you call it, you can pass different “parameters” –Subs can return results –Subroutines are called with & sub sayhi { print(“Hello world\n”); print(“Hello world\n”);}&sayhi;

10 Subroutine scope The inner workings of a subroutine should be hidden from the rest of the script The inner workings of a subroutine should be hidden from the rest of the script –Think of a sub as a black box  When you turn on your TV, you don’t care about what’s happening inside it, you just expect it to produce pictures and sound.  Thus you need to ensure that any variables you use inside a sub are hidden from the outside world –It’s suck if your TV changed channel just because your neighbor changed his TV. If the “$CurrentChannel” variable in your TV was the same as the “$CurrentChannel” variable in your neighbors TV, this might just happen. –To ensure that variables are hidden inside your sub, use these special keywords to indicate your variables are just for this sub:  my  local –There is a slight difference between them, however it’s unimportant for now, use my for all scalars, and local for all arrays and hashes.

11 Passing parameters Each sub you define automatically gets an array passed to it called @_ Each sub you define automatically gets an array passed to it called @_ –This array contains anything you pass to the sub when you call it. sub add2numbers { my($Num1,$Num2)=@_; my($Num1,$Num2)=@_; $Answer=$Num1+$Num2; $Answer=$Num1+$Num2; return($Answer); return($Answer);}$Result=&add2numbers(17,3); print(“17 + 3 = $Result\n”); $Result2=&add2numbers(32,8); print(“32 + 8 = $Result2\n”);

12 Getting results To stop working in a subroutine and return to wherever you called it from, you simply say: To stop working in a subroutine and return to wherever you called it from, you simply say:return; If you need to send back results, you’d say: If you need to send back results, you’d say:return(17);return($Answer);return($Answer1,$Answer2);return(@LotsOfAnswers); To get the results, you’d have assigned the call to the sub to a variable, or list of variables: To get the results, you’d have assigned the call to the sub to a variable, or list of variables:$Answer=⊂($Answer1,$Answer2)=⊂(@Answers)=⊂

13 One weirdness If you need to pass an array + (a scalar, or another array) to a sub, there is a problem. If you need to pass an array + (a scalar, or another array) to a sub, there is a problem. –Because of the way that all parameters to a sub are magically sent via @_, if you send 2 arrays, @_ doesn’t know where one starts and the other ends, so you’ll end up with a single array. This is probably not what you want –There are 2 solutions to this depending on what you are doing.  If you are sending an Array and some Scalars, be sure to send the scalars FIRST, and the Array LAST. –This will work fine:  my($Var1,$Var2,$Var3,@Array1)=@_; –This will not:  my(@Array1,$Var1)=@_; ($Var1 will end up empty) –If you must send 2 arrays do it like this:  my(*Array1,*Array2)=@_; –Call it like this:  &Sub(*Arr1,*Arr2);

14 Sorting by value In our last example, we got a list of all the names, and how many people have each name, but what if you want that sorted by the most popular names? In our last example, we got a list of all the names, and how many people have each name, but what if you want that sorted by the most popular names? @FirstNames=('Lucas','Fay','Robert','Dan','Kashika','Jeremy','Spencer','Scott','Michael','Sur esh','Kris','Chad','Michael','Scott','Michael','Rich','Shawn','Wes','Jeff','Adam','Hyun Jin','Sean','Enda'); foreach $Name (@FirstNames) { $NameCount{$Name}++; $NameCount{$Name}++;} sub SortByValue { $NameCount{$b} $NameCount{$a}; $NameCount{$b} $NameCount{$a};} foreach $PopularName (sort SortByValue keys %NameCount) { print("There are $NameCount{$PopularName} people named $PopularName\n"); print("There are $NameCount{$PopularName} people named $PopularName\n");}

15 Next and Last When you are in a loop, sometimes you just want to stop abruptly When you are in a loop, sometimes you just want to stop abruptly –Loops have 2 controls:  last; –This exits the loop immediately, and continues past the closing }  next; –This stops this iteration of the loop, and moves onto the next, restarting at the { Imagine you want the top 3 most popular names Imagine you want the top 3 most popular names –Change our last example to this: $Count=0; foreach $PopularName (sort SortByValue keys %NameCount) { $Count++; $Count++; print("There are $NameCount{$PopularName} people named $PopularName\n"); print("There are $NameCount{$PopularName} people named $PopularName\n"); if($Count>3) if($Count>3) { last; } { last; }}


Download ppt "Perl Day 5. Arrays vs Hash Arrays are one way to store multiple things in a variable. Hashes are another. Arrays are one way to store multiple things."

Similar presentations


Ads by Google