Upload
kristopher-benson
View
212
Download
0
Embed Size (px)
Citation preview
PerlPerl
Day 5Day 5
Arrays vs HashArrays vs Hash Arrays are one way to store multiple things in a Arrays are one way to store multiple things in a
variable. Hashes are another.variable. Hashes are another.– In an array, the elements in the array are automatically In an array, the elements in the array are automatically
numbered, 0, 1, 2, 3….numbered, 0, 1, 2, 3….– In a hash, you can decide what they are calledIn a hash, you can decide what they are called– Hashes start with a % instead of a @Hashes start with a % instead of a @– You use => to indicate what belongs to what.You use => to indicate what belongs to what.– When you want to pull the answer back you use When you want to pull the answer back you use
$hash{key}$hash{key}%FruitColors=(%FruitColors=('apple' => 'green','apple' => 'green','banana' => 'yellow','banana' => 'yellow','orange' => 'orange');'orange' => 'orange');
print("Apples are $FruitColors{apple}\n");print("Apples are $FruitColors{apple}\n");
KeysKeys Each array element is said to have a “key” Each array element is said to have a “key”
and a “value”.and a “value”.– In the previous example, the fruit name (apple, In the previous example, the fruit name (apple,
banana etc) are keys. The colors are “values”.banana etc) are keys. The colors are “values”.– You can get the list of “keys” in a hash with the You can get the list of “keys” in a hash with the
keys command. It returns an array:keys command. It returns an array:@Fruits=keys %FruitColors;@Fruits=keys %FruitColors;– You can also use a loop show all of them:You can also use a loop show all of them:foreach $Fruit (keys %FruitColors)foreach $Fruit (keys %FruitColors){{ print(“$Fruit is $FruitColors{$Fruit}\n”);print(“$Fruit is $FruitColors{$Fruit}\n”);}}
sortsort
Sometimes you want your fruits Sometimes you want your fruits alphabetized:alphabetized:
The fruits in order are:The fruits in order are:
foreach $Fruit (sort keys %FruitColors)foreach $Fruit (sort keys %FruitColors)
{{
print(“$Fruit is $FruitColors{$Fruit}\print(“$Fruit is $FruitColors{$Fruit}\n”);n”);
}}
Uses for HashesUses for Hashes Lets imagine you had of the first name of everyone in our Lets imagine you had of the first name of everyone in our
office. You might want to know how many people named office. You might want to know how many people named “Michael” we have.“Michael” we have.
All Hash values start off as 0, so you can simply add 1 to All Hash values start off as 0, so you can simply add 1 to them each time you find a Michaelthem each time you find a Michael
@FirstNames=(‘michael’,’adam’,’enda’,’lucas’,’fay’,’michael’,’@FirstNames=(‘michael’,’adam’,’enda’,’lucas’,’fay’,’michael’,’michael’,’spencer’,’kris’);michael’,’spencer’,’kris’);
foreach $Name (@FirstNames)foreach $Name (@FirstNames){{ $NameCount{$Name}++;$NameCount{$Name}++;}}foreach $FirstName (keys %NameCount)foreach $FirstName (keys %NameCount){{ print(“There are $NameCount{$FirstName} people named print(“There are $NameCount{$FirstName} people named
$FirstName\n”);$FirstName\n”);}}
Removing something from a Removing something from a hashhash
If you need to get rid of something If you need to get rid of something out of a hash, you use deleteout of a hash, you use delete
delete($FruitColor{banana});delete($FruitColor{banana});
AbstractionAbstraction
One of the most important concepts in One of the most important concepts in doing a big task is Abstraction.doing a big task is Abstraction.
– Imagine I told you to build this building. How Imagine I told you to build this building. How would you do it?would you do it?1.1. Hire an architectHire an architect
2.2. Buy some landBuy some land
3.3. Hire a contractor to oversee building itHire a contractor to oversee building it
– Note the details of how the contractor hires Note the details of how the contractor hires his people etc are not important right now.his people etc are not important right now. This is abstraction, solving smaller problems, which This is abstraction, solving smaller problems, which
will ultimately allow you to solve the bigger will ultimately allow you to solve the bigger problem.problem.
Abstraction in programmingAbstraction in programming Likewise when asked to write a big script, you Likewise when asked to write a big script, you
don’t just try to do it all at once. don’t just try to do it all at once. – Do all the little parts you know how to do firstDo all the little parts you know how to do first– Use those building blocks to solve the bigger problemUse those building blocks to solve the bigger problem– Examples of how to break things upExamples of how to break things up
Dealing with @ARGVDealing with @ARGV Opening a file and reading it’s contents, putting them into Opening a file and reading it’s contents, putting them into
an arrayan array Doing some regular expression magic to figure something Doing some regular expression magic to figure something
outout Writing out the result to a file.Writing out the result to a file.
– There is no single right answer on how things should be There is no single right answer on how things should be broken up, but a good rule of thumb is if you can’t broken up, but a good rule of thumb is if you can’t explain in 1 sentence what something it doing, it should explain in 1 sentence what something it doing, it should be broken up into smaller tasks.be broken up into smaller tasks.
Sub tasksSub tasks In perl each sub task is called a subroutine (sub for In perl each sub task is called a subroutine (sub for
short)short)– Each has a name, you should call it something descriptiveEach has a name, you should call it something descriptive– Subroutines can be used over an over (that’s the whole Subroutines can be used over an over (that’s the whole
point)point) Each time you call it, you can pass different “parameters”Each time you call it, you can pass different “parameters”
– Subs can return resultsSubs can return results– Subroutines are called with &Subroutines are called with &sub sayhisub sayhi{{ print(“Hello world\n”);print(“Hello world\n”);}}
&sayhi;&sayhi;
Subroutine scopeSubroutine scope The inner workings of a subroutine should be The inner workings of a subroutine should be
hidden from the rest of the scripthidden from the rest of the script– Think of a sub as a black boxThink of a sub as a black box
When you turn on your TV, you don’t care about what’s When you turn on your TV, you don’t care about what’s happening inside it, you just expect it to produce pictures happening inside it, you just expect it to produce pictures and sound.and sound.
Thus you need to ensure that any variables you use inside Thus you need to ensure that any variables you use inside a sub are hidden from the outside worlda sub are hidden from the outside world
– It’s suck if your TV changed channel just because your It’s suck if your TV changed channel just because your neighbor changed his TV. If the “$CurrentChannel” variable in neighbor changed his TV. If the “$CurrentChannel” variable in your TV was the same as the “$CurrentChannel” variable in your TV was the same as the “$CurrentChannel” variable in your neighbors TV, this might just happen.your neighbors TV, this might just happen.
– To ensure that variables are hidden inside your sub, use To ensure that variables are hidden inside your sub, use these special keywords to indicate your variables are these special keywords to indicate your variables are just for this sub:just for this sub: mymy locallocal
– There is a slight difference between them, however it’s There is a slight difference between them, however it’s unimportant for now, use my for all scalars, and local for unimportant for now, use my for all scalars, and local for all arrays and hashes.all arrays and hashes.
Passing parametersPassing parameters Each sub you define automatically gets an array passed to Each sub you define automatically gets an array passed to
it called @_it called @_– This array contains anything you pass to the sub when you call This array contains anything you pass to the sub when you call
it.it.
sub add2numberssub add2numbers{{ my($Num1,$Num2)=@_;my($Num1,$Num2)=@_; $Answer=$Num1+$Num2;$Answer=$Num1+$Num2; return($Answer);return($Answer);}}
$Result=&add2numbers(17,3);$Result=&add2numbers(17,3);print(“17 + 3 = $Result\n”);print(“17 + 3 = $Result\n”);$Result2=&add2numbers(32,8);$Result2=&add2numbers(32,8);print(“32 + 8 = $Result2\n”);print(“32 + 8 = $Result2\n”);
Getting resultsGetting results To stop working in a subroutine and return to To stop working in a subroutine and return to
wherever you called it from, you simply say:wherever you called it from, you simply say:return;return; If you need to send back results, you’d say:If you need to send back results, you’d say:return(17);return(17);return($Answer);return($Answer);return($Answer1,$Answer2);return($Answer1,$Answer2);return(@LotsOfAnswers);return(@LotsOfAnswers); To get the results, you’d have assigned the call to To get the results, you’d have assigned the call to
the sub to a variable, or list of variables:the sub to a variable, or list of variables:$Answer=⊂$Answer=⊂($Answer1,$Answer2)=⊂($Answer1,$Answer2)=⊂(@Answers)=⊂(@Answers)=⊂
One weirdnessOne weirdness If you need to pass an array + (a scalar, or another If you need to pass an array + (a scalar, or another
array) to a sub, there is a problem.array) to a sub, there is a problem.– Because of the way that all parameters to a sub are Because of the way that all parameters to a sub are
magically sent via @_, if you send 2 arrays, @_ doesn’t magically sent via @_, if you send 2 arrays, @_ doesn’t know where one starts and the other ends, so you’ll end up know where one starts and the other ends, so you’ll end up with a single array. This is probably not what you wantwith a single array. This is probably not what you want
– There are 2 solutions to this depending on what you are There are 2 solutions to this depending on what you are doing.doing. If you are sending an Array and some Scalars, be sure to send If you are sending an Array and some Scalars, be sure to send
the scalars FIRST, and the Array LAST. the scalars FIRST, and the Array LAST. – This will work fine:This will work fine:
my($Var1,$Var2,$Var3,@Array1)=@_;my($Var1,$Var2,$Var3,@Array1)=@_;– This will not:This will not:
my(@Array1,$Var1)=@_; ($Var1 will end up empty)my(@Array1,$Var1)=@_; ($Var1 will end up empty)
– If you must send 2 arrays do it like this:If you must send 2 arrays do it like this: my(*Array1,*Array2)=@_;my(*Array1,*Array2)=@_;
– Call it like this:Call it like this: &Sub(*Arr1,*Arr2);&Sub(*Arr1,*Arr2);
Sorting by valueSorting by value In our last example, we got a list of all the names, and how many people 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 have each name, but what if you want that sorted by the most popular names?names?
@FirstNames=('Lucas','Fay','Robert','Dan','Kashika','Jeremy','Spencer','Scott','@FirstNames=('Lucas','Fay','Robert','Dan','Kashika','Jeremy','Spencer','Scott','Michael','Suresh','Kris','Chad','Michael','Scott','Michael','Rich','Shawn','Wes',Michael','Suresh','Kris','Chad','Michael','Scott','Michael','Rich','Shawn','Wes','Jeff','Adam','Hyun Jin','Sean','Enda');'Jeff','Adam','Hyun Jin','Sean','Enda');
foreach $Name (@FirstNames)foreach $Name (@FirstNames){{ $NameCount{$Name}++;$NameCount{$Name}++;}}
sub SortByValuesub SortByValue{{ $NameCount{$b} <=> $NameCount{$a};$NameCount{$b} <=> $NameCount{$a};}}
foreach $PopularName (sort SortByValue keys %NameCount)foreach $PopularName (sort SortByValue keys %NameCount){{ print("There are $NameCount{$PopularName} people named print("There are $NameCount{$PopularName} people named
$PopularName\n");$PopularName\n");}}
Next and LastNext and Last When you are in a loop, sometimes you just want to stop When you are in a loop, sometimes you just want to stop
abruptlyabruptly– Loops have 2 controls:Loops have 2 controls:
last;last;– This exits the loop immediately, and continues past the closing }This exits the loop immediately, and continues past the closing }
next;next;– This stops this iteration of the loop, and moves onto the next, This stops this iteration of the loop, and moves onto the next,
restarting at the {restarting at the { Imagine you want the top 3 most popular namesImagine you want the top 3 most popular names
– Change our last example to this:Change our last example to this:$Count=0;$Count=0;foreach $PopularName (sort SortByValue keys %NameCount)foreach $PopularName (sort SortByValue keys %NameCount){{ $Count++;$Count++; print("There are $NameCount{$PopularName} people print("There are $NameCount{$PopularName} people
named $PopularName\n");named $PopularName\n"); if($Count>3)if($Count>3) { last; }{ last; }}}