1

Chapter 8 – Perl Regex Operators

-

Chapter 7 – Perl Regex Operators

Too put it simply, a regex unlocks the power to complete string comparisons. That is, it gives us full control over how we view and manipulate any string (variable) we have. Regexes is short for Regular Expressions and it takes even advanced programmers a while to understand these well enough to code them efficiently and accurately.

Regular expressions is one of the reasons Perl is such a powerful language, mastering these will give you full control over the data you’re using through your scripts. Before we begin, here is a simple regex for us to look at.

$variable =~ s/text/TEXT/gi;


The m// operator

The m// operator is how we deal with matching. This is used against the default variable $_ by default but implementing another variable is just as easy as inserting the variable name. This matching operator works well when you need to know if a string contains a certain character, group of characters or word or a group of words. Instead of saying if ($line eq “test”) which will not work if all we want to know if is the word test exists in $line, we would use m// instead.

The main difference between a simple eq or == and a m//, is one tests for equality and the other tests for the existance of the value inside the string.

my $line;
while($line = <STDIN>)
{
if($line =~ m/exit/) { exit; }
}

This example acts as an infinite loop until it matches what we’re looking for. It’s asking for input, unless the line contains the word exit it’s not going to end for us. From this you can see where our search gets used; the characters or words we want to match are placed inside the //.

my $text = “a blue cow ate the cheese”;
if ($text =~ m/cow/)
{
print “mooooooo”;
}

We are taking a predefined variable $text and seeing if we can match the word cow anywhere in it. As we can see, while running this code we’ll get mooooo back because it can find the word.

Remember, this matching operator doesn’t test for equality, it checks for the existence.


The s/// operator

The second most used operator is the substitution operator. This gives us the power and tools to manipulate our information in any way we wish. We could scan an entire text file and change all the words “red” to “blue” if that’s what we wanted.

This works hand-in-hand with the m/// we just learned in the fact that our words either exist and we can do something with them, or they don’t. This is to say, we can’t substitute any part of our text unless the text we want to change already exists.

my $line;
while($line = <STDIN>)
{
  chomp($line);
  $line =~ s/exit/go/;
  print “Did you say $line?\n”;
}

We’re doing a bit more work in this example because there is a lot more to a substitution than to match words or phrases. This is nearly the same example we used before, if you type any phrase containing the word exit something will happen. In this case, we are s/exit/go which means if it finds the word exit, it will be replaced with the word go.

The best way to learn is to do, so run this script a few times and run a few tests. Type in words that don’t contain exit and some that do so you get familiar with what’s going on.

Unlike the match operator where we have m/word/, we have a new set s/word/neword/. The second set of slashes is the replacement words/characters for what you asked for in the first set.

s/this/that; # change the word from this to that
s/apple/pear; # change the word apple to pear
s/I have a red car/I have a red bike/; # change the entire sentence if it matches

A few things to note before we move on is our s/// will only work once by default and is case-sensitive. Put simply, if we tried to change the word this to that, by default it will only change the first occurance of this and leave the rest untouched and it will not match THIS.

my $text = “the rabbit jumped down the hole where the cow lived.”;
$text =~ s/the/THE/;
print $text;

This example substitutes the lowercase word the to the uppercase THE. By running this script you’ll notice that only the first the that’s found gets replaced giving us the result: THE rabbit jumped down the hole where the cow lived.

my $text = “the rabbit jumped down the hole where the cow lived.”;
$text =~ s/the/THE/;
print $text;

Using /g at the end of our substitution means to substitute globally, instead of just matching the first instance of the word or phrase we’ll substitute it for each time it appears in our data. Taking the same sentence we used before, simply by adding the /g modifier to the end will replace every occurrence of the word the and end with the result: THE rabbit jumped down THE hole where THE cow lived.

my $text = “The rabbit jumped down the hole where the cow lived.”;
$text =~ s/the/THE/gi;
print $text

With making the small change to our sentence (we capitalized the T on The on the first word), our substitution would normally skip this and replace only the because it’s match is case sensitive. The /i modifier changes the default to a case-insensitive substitution. This will s/// (short for substitute) the words The, THe, tHe and so forth with THE and since we’re still using the global modifier /g, it will change all instances of these words.

Sometimes we want to just remove certain words or phrases instead of just s/// them with another word or phrase. This can be done by leaving the second set of slashes empty. Doing so tells Perl that you want to substitute the first set of words for nothing (an empty substitution), therefore removing the words completely.

my $text = “The rabbit jumped down the hole where the cow lived.”;
$text =~ s/the/gi;
print $text;

In this last example, we’re removing the word the in any case and as many times as it can be found in the string. This will produce the results:

rabbit jumped down hole where cow lived


The tr/// operator

The translation operator also works on $_ by default, with this we can make a character-by-character translation. The s/// worked on words, numbers and phrases. This operator works on characters solely.

my $line;
while($line = <STDIN>)
{
  chomp($line);
  $line =~ tr/1/0/;
  print “Did you say $line?\n”;
}

We are translating each occurrence of the character “1″ with “0″. Similar with s///, the 2nd set of slashes is what we’re converting our data into if it matches. For another simple example,

my $text = “bear”;
$text =~ tr/b/t/;
The above gives us the result tear as we are replacing the character “b” with “t”.

We can remove characters we want from our string instead of swapping it for another. We do this using the /d (delete) modifier. We create the character group we want to translate, leave the second set of slashes empty and append d.

my $text = “This is a line of text”;
$text =~ tr/a//d;
print “results: $text”;

Take not the second set of slashes // are to be left empty if you want to delete the characters instead of swapping them with another. In our example above, we removed all the “a”s from our text, which was just one however. A better example would have been to remove an “i” or an “e”, but I’ll leave that up to you to test.

We now have a fairly good understanding of swapping one character with another, Perl allows us to swap more than one at a time. This is to say, we can tr/// as few (if greater than one, of course) or as many characters at a time as we want.

my $text = “This is the line that never ends. Yes it goes on and on my friend. Some people started writing it, not knowing what it was. And they’ll continue writing it forever just because…this is the line that never ends!”;

$text =~ tr/th/ht/d;
print “results: $text”;

You will notice we are translating two different characters, the T and the H. We are swapping them with H and T. You can swap as many or as little as you want like we discussed earlier, but keep in mind it’s in a set order. The first character in the first set will swap with the first character in the second set (our “t” was swapped with “h”), the second character in the first set will always swap with the second letter in the second set (our “h” swapped with “t”).

This example let us switch the H’s and T’s around making funny text :) These are case sensitive too, tr/A// will not be the same as tr/a// and as of the time of writing this, I don’t know of a case-insensitive modifier to remedy this. So you’ll need to use tr/Aa// if you want to catch all of the same character.

Four our last example, let’s have a little fun and remove all the vowels from our text! We would do that by adding each of the vowels to the first set of // and appending the delete modifier.

my $text = “This is the line that never ends. Yes it goes on and on my friend. Some people started writing it, not knowing what it was. And they’ll continue writing it forever just because…this is the line that never ends!”;

$text =~ tr/aeiou//d;
print “results: $text”;
We get the results:

Ths s th ln tht nvr nds. Ys t gs n nd n my frnd. Sm ppl strtd wrtng t,
nt knwng wht t ws. And thy’ll cntn wrtng t frvr jst bcs…ths s th ln tht nvr
nds!

Challenges

1) Of the three regex operators we learned, which one(s) does not alter the data in any way?
————————————————————————
The m// match operator only matches segments of a string, s/// and tr/// are used to change the data.
————————————————————————

2) We are trying to remove all the “a”s from our variable $sentence using s/// but it’s not removing “A”. How can we remove all cases?
————————————————————————
We need to setup a case insensitive substitution. We do this using the case-insensitive modifier, /i.

$sentence =~ s/a/gi;
————————————————————————

3) What is the difference between substitution and translation?
————————————————————————
Substation, or s///, replaces words, numbers or phrases from a string. Translation, or tr///, only translates or swaps characters.

An example of s/// would be: s/word/this/gi, s/apple/pear/gi, s/moon is out/sun is out/gi.

An example of tr// would be: tr/a/e/, tr/1/0/, tr/x/z.
———————————————————————–

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
3

Chapter 7 – Perl Loops

-

Chapter 7 – Perl Loops

In previous lessons we discussed the various data types and a few brief looping examples. In Perl we can execute a portion of code any number of times we specify or we can execute a portion of code whether our given test succeeds or fails. Many times in our applications we want to test the accuracy of given information (such as a password authenticator).


IF/ELSE/ELSIF

These three aren’t really loops.  Instead they are actually iterators meaning they will only be run one time- and one time only. A loop is something that runs over a particular piece of code more than one time, but these are widely accepted and considered as loops and people will understand what you mean if you refer to them as so.

my $password = “test”;
if ($password eq “test”)
{
  print “Our password was test”;
}

Our small example above shows a simple conditional test. IF $password EQUALS test { … }.

We are testing our variable $test to see if it contains the exact string “test”. If our test passes, everything inside the { and } will be executed. You can print statements like we did, do mathematical equations, redirect the user to a new page, store cookies, etc. You can do as many or as little as you want, you can print out 100 different lines of code, but whatever you do.. it will only execute if our test succeeds.

Everything between the parenthsis is the test, everything between the { } is what will happen depending on whether the test passes or fails.  In our example, we only printed information if our password equaled test and nothing happened if it didn’t. Running this program with a wrong password wouldn’t produce any information making the end user think the script crashed. Let’s print out a message if the password is wrong so they know what happened.

my $password = “test”;
if ($password eq “test”)
{
print “Our password was test”;
}
else
{
print “The password you entered was incorrect”;
}

What we did was add an else clause after our end bracket in if. We don’t need to setup a second test since IF and ELSE work in conjunction with one another. If for whatever reason the test fails, everything in the else { } will be executed. Let’s now change the above example to intentionally fail on us so we can catch the else.

my $password = “test”;
if ($password eq “jello lollipop”)
{
  print “Our password was test”;
}
else
{
  print “The password you entered was incorrect”;
}

Simply put, we are testing to see if our password that has been assigned the value “test” is equal to “jello lollipop”. It should go without saying two values are different and this will fail and print: The password you entered was incorrect.


ELSIF:
Some times an IF/ELSE isn’t enough control for applications. Let’s say, for example, we want to check to see if someone knows your name and can type it in (in all lowercase OR all uppercase).

#### $guessed_name is assuming you have one setup already, we didn’t create it here
if ($guessed_name eq “robert”)
{
  print “You got my name right!”;
}
elsif ($guessed_name eq “ROBERT”)
{
  print “You still got my name right!”;
}
else
{
  print “Ooops, you don’t know my name afterall”;
}

The snippet above is really doing two tests. If the first test if(…) doesn’t succeed, the elsif will be given a turn. In our example, pretend $guessed_name equals “ROBERT”. The elsif will catch on and say: “You still got my name right!” even though the initial test failed. Now, if my name equaled “RoBert” both the tests would have failed and else would have kicked in and printed out our little error message. 

Elsif requires a second test in parenthesis because it is given the chance to see if a different piece of information returns true.

Else doesn’t require a separate test because this happens if nothing else works.


Unless

Unless will run code based on a test. The code will not run UNLESS the test is justified.

my $guessed_name = “RobErt”;
unless ($guessed_name eq “robert”)
{
  print “You apparently don’t know my name!”;
}

In simple terms, this is really saying “If $guessed_name does NOT equal robert, do the following”. Regardless of what $guessed_name really was, if it’s not exactly “robert” the code will be executed and you’ll be yelled at for not knowing my name. So unless the test is true, the code will be processed.

For

A for loop lets you execute a chunk of information or processes that fit a given pattern. Let’s say we wanted to impress people in our school and show them we know how to count in Perl, but we don’t want Perl to count endlessly. We’ll need some way to stop the loop. For loops are an excellent way to run over a certain piece of code any number of times you want.

In the example below, we are counting from 1-20.

my $number = 0;
for (1 .. 20)
{
$number++;
  print “I can count: $number\n”;
}

We are using a range operator in our loop; a range operator is a number .. number as you can see between our parenthesis. This means for these numbers, 1-20, do the following code. In the end, it will process whatever we asked it to exactly twenty times (1-20 is 20 numbers).

The rest of the script should look pretty familiar if you have been following all the lessons. We’re setting our variable $number to zero before our loop, then each time our loop goes through it will add +1 to the current number nad print it back to the screen. You don’t necessarily have to use positive numbers, the range ( -10 .. -1) will loop exactly 10 times and will produce our numbers from the last script accurately. Now, because programmers typically like to condense code as much as possible, you can shrink the number of lines in our last example down some. This is one of those things that may be confusing for you until you get the chance to play with them a few times in your scripts.

#!/usr/bin/perl

for (my $number = 1; $number <=20; $number++)
{
  print “I can count: $number\n”;
}

This alternative method is taking three expressions. Each expression is separated by a semicolon and this is virtually doing the exact same thing as our previous example. Only difference is we’re doing all the calculations and variable settings inside the for loop parenthesis rather than before and inside the squirrely brackets.  We are setting our variable in expression 1, in our case we set this to the number 1 for simplicity. The second expression acts almost like a while loop which we haven’t learned yet. While the current $number is less than or equal to the number 20, we will do whatever is in expression 3 and run our code between the { }. We have to auto increment $number in expression 3 otherwise $number would never get incremented and we’d be tossed into an endless loop.  And endless loop is something we all fear, it’s a loop that begins but will not stop. This happens typically by a misjudgment in our coding, but there are times were you’ll intentionally do such a thing. A really quick example of an endless loop is:

my $number = 1;
while ($number == 1)
{
print “This is the string that never ends!!\n”;
}


Foreach

The foreach loop is the one I use most often as it’s a very handy tool while debugging your scripts whether they be in Perl or CGI. This will loop over every item in an array or a hash and allow you to print or manipulate the data in any way you wish.

my @array = (“Minnesota”, “Iowa”, “Wisconsin”, “California”)’

foreach(@array)
{
  print “$_\n”:
}

We are pulling in a list of information from our @array and executing them one at a time. Remember that whatever you do with your code inside of a foreach will be applied to every item it comes by. We are printing each array element using $_, notice we only have to include one print statement for each of them to print to screen at run time.This is what makes this such a powerful tool. It lets you print full arrays and full hashes quickly and easily. What you wish to do each time it finds a piece of information is up to you, but to keep simplicity all we did was print them.

Below is an example using a hash:

my %hash = (“Minnesota” => “1″, “Iowa” => “2″, “Wisconsin” => “3″, “California” => “4″);

foreach (keys %hash)
{
print “$_ => $hash{$_}\n”;
}

This isn’t much different than printing an array but we’re using keys inside the foreach (). If you want to learn more about arrays and hashes, please see the other tutorials written on these datatypes.


Until

Until is one of the select loops that could be used to create an infinite loop if you’re not careful and the test/condition never passes.

Just as the name suggests, an until() loop will loop over the chunk of code within your braces UNTIL a condition is met.

my $count = 0;
until($count eq “5″)
{
  $count++;
};

The above code will continue to auto increment our $count variable until our condition is met (when $count eq 5).


Other important information

If you are trying to compare two strings to see if they are identical, you’d use eq such as:

my $name = “robert”;

if ($name eq “robert”)
{
print “You know my name!”;
}
If you were trying to see if a variable had the value of a number, you use == (a double equal sign)

my $number = “4″;

if ($number == “4″)
{
  print “Correct!!”;
}

Keep in mind we are testing values, if you tried to use a single = sign the script would pass or fail depending on how you look at it. A = is an assignment operator, it assigns the value to the right. eq and == are comparison operators, they see if they match up but won’t assign the value.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
0

Chapter 6 – Perl Hashes

-

Chapter 6 - Perl Hashes

Hashes are the third and final type of variable used to store data in Perl. A hash is also known as an associative array as it is similar to the array discussed in the previous lesson in the way it can hold lists of information. The primary differences are the key/value pair combinations.

Hashes store information using KEY/VALUE pairs and does not use numbered indexing like arrays do.

Hashes use % in the same way arrays use @ and scalars use $. Similar to arrays, when dealing with a single piece of data in a hash it is referenced with the $ scalar sign.

To make a hash, two bits of information are needed. The KEY and the VALUE. Using arrays, the array name itself acted as the key, with hashes every pair (key value pair) has their own key.

@colors = (“red”, “brown”, “purple”, “pink”);

The array @colors is a list containing the values red, brown, purple and pink. @colors acts as the key in the sense that all of the data (color names) are connected and retrieved from it.


Creating a hash

my %names = (“Fred” => “Flintstone”);

The hash named %names above has a key of Fred and a value of Flintstone. The key is always the first item in the key/value pair. There are a few other ways of setting up the same hash:

my %names = (“Fred” , “Flinttstone”);
my %names = qw(Fred Flinstone);

These are just two of many other ways of setting up hashes. Please take note that the first and second example are identical. The => in Perl represents a literal comma (,). Some programmers prefer this over using the comma because => stands out which makes it easier to see which piece is the key and which is the value. Because it’s easier to see, this tutorial will primarily be using this method.

In most cases, Perl ignores whitespace except when it’s in a double quoted string. You’ll find most programmers setting up a hash looking like the one below. Because Perl ignores the whitespace, the programmer is given the choice to write the code in a format they like and understand.

my %food = (
                     ”warm” => “oatmeal”,
                     ”hot” => “steak”,
                     ”cold” => “ice cream”
);

Since white spaces aren’t important we aligned our data in a one-per row, comma separated list. The last key/value pair in a hash does not have a trailing comma. Commas are used to separate key/value pairs, not end them.

If this layout is too much to remember at this point, they can be written similar to an array, such as:

my %food = (“warm” => “oatmeal” , “hot” => “steak”, “cold” => “ice cream”);

However it is written is completely up to the programmer. Some prefer to keep things on one line while others prefer to keep everything separated as much as possible.

Each hash key must be unique. Using the %food hash above, every key is unique (warm, hot, cold). If one were to assign another set warm => toast it will erase the warm => oatmeal. Every key in a hash is unique. You will never be able to have two of the same name. Values can be repeated an infinite number of times without problems arising.


Printing hashes

You can retrieve the value of a hash key by calling its key name inside the brackets of $hash{}. For example, using the same %food we made earlier, we want to print out the value “steak”. Since steak is tied to the key hot, we would write:

print $food{“hot”};

The above code would print steak since steak is the value of the key hot. If we used print $food{“cold”}, it would have returned the value ice cream.

Printing the entire hash can be a little difficult for someone just beginning in Perl. You could, if you didn’t care of the format, print %hash; and use the results. The problem with this method is there aren’t any spaces between any of the keys or values. If you printed %food like that, the result would be one1two2.

The quickest way to print a complete hash is tossing it into a foreach loop. A foreach loop iterates (passes over) each element and applies whatever command you want. This looping structure is not within this lesson’s outlines so we’re not going into great detail about it at this point. In the example below, we are passing over every key/value pair in

foreach(keys %hash)
{
   print “$_ => $hash{$_}\n”;
}

Let’s discuss this line by line. We begin the foreach loop foreach() telling it to iterate over each keys in the %hash. Remember, a key is the first item in a key/value pair. So, for every key it passes in %hash, it will apply whatever we set in our brackets {}.

$_ is a special variable used by Perl to store information temporarily. Each time it comes across another key, it’s data is stored in $_. The first thing that iterates in our hash would be “warm” => “oatmeal”, warm will be stored inside of $_ until your print is done and it moves onto the next.

Remember, => in this case isn’t a comma. If it’s used inside a set of quotations, it prints exactly as it looks: =>. Now we move on to $hash{$_}. Here we see the special $_ variable again, this means the information that was currently stored in $_ is now deleted and is now being used to keep our new data. If $_ is they hash key, $hash{$_} is the hash value.

The \n at the end is the linefeed character, it acts the same way as the <br> tags do in HTML. Putting it at the end of the line means it will print one key/one value per line. Here is an example.

my %weather = (
  “yesterday” => “cold”,
  “today” => “snowy”,
  “tomorrow => “tropic”
);

foreach(keys %weather)
{
  print “$_ => $weather{$_}”;
}

Adding to a hash

Adding information into a hash is much easier than adding data into an array, and in many ways it’s a lot more efficient. You no longer have to worry on how many indexes you have and there is no need to count how many items are in the list. Data is assigned in a key/value pair.

$hash{$key} = $value;

Let’s make a hash using the first name as the key and the last name as the value. Then we realize we forgot our little friend Santa Clause, and just so we’re sure we don’t get coal next Christmas, we decide to add his name for good graces.

my %names = (
“Frosty” => “Snowman”,
“Easter” => “Bunny”,
“Big” => “Bird”
);

$names{‘Santa’} = “Claus”;

Since we are adding one string (key/value), we call names with its $ scalar sign. Remember, the key comes before the value so we’re setting “Santa” => “Claus”. Don’t forget to use your tick marks surrounding your key.

One thing to keep in mind is you better make sure each and every one of your keys are unique. You cannot use $name{‘Fred’} = “Flintstone” and $name{‘Fred’} = “Bush” in the same hash, otherwise only one of the two will be used correctly and the other one will be ignored (to be more technical, the one that appears is the last pair that shares a common key. In this case, Fred => Bush would be read, Fred Flintstone will be over-written.


Deleting hash pairs

Deleting items from a hash is not much different than adding to the hash itself. We call the delete method on the hash key. Since the key and value are paired together, by deleting the key you are actually removing the key/value pair.

delete $hash{$key};

From our last example, it turns out our parents told us the Easter Bunny isn’t real :( So we may as well remove him from our list.

delete $hash{‘Easter’};

The value Bunny is connected to Easter, so they are both permanently removed.

If you try to delete a key that doesn’t exist, nothing happens. Obviously it won’t delete it if it can’t find the exact key you’re looking for, but it won’t give you an error saying it didn’t exist either. (not until the next section when we talk about existence).


Testing for existence

One thing you’ll find yourself having to do over and over again when using hashes is testing to see if a certain key exists. This is easily done by using an if/else iteration. We have not gone over any looping structures yet and this is the best one to start out with.

If/Else will read the parameters you are testing, and if it proves to be what you are testing for, it will do whatever you tell it to in the first set of {} brackets. If for any reason the test didn’t go successful, the else is activated and the code between the last set of {} is activated.

if (test)
{run this code if our test passes}
else
{run whatever is in here if it fails}

That is a naked If/Else. Following the if is where you set up your test in parenthesis. The test can be virtually anything you want to test against, but for this lesson we’re only going to be learning how to test for the existence of hash elements.

Exist is the method we use to test the existence of a key in a hash. Perl is pretty consistent when it comes to naming their methods which makes them a lot easier to remember and on occasion, easier to guess.

if(exists $hash{$key})
{ if the hash key exists, this will run}
else
{if this section is activated, it means $hash{$key} doesn’t exist}

if() is where our test begins. We are testing for exists $hash{$key}. If it exists, our first set of {} is activated and used and if it doesn’t exist, the second set does.

Let’s try a real example now:

my %pop = (
“Mello Yello” => “good”,
“Pepsi” => “nasty”,
“Mountain Dew” => “pure as gold”
);

if (exists $pop{‘Pepsi’})
{ print “Yes, Pepsi exists!”; }
else
{ print “No, Pepsi doesn’t exist”; }

We are testing for the existence of the key Pepsi. If you made the same hash as the example, you will notice we DO in fact have a key called ‘Pepsi’. That means if you run this script, the first set of {} will be used and the print statement “Yes, Pepsi exists!” will show on your screen.

if (exists $pop{‘Vanilla Coke’})
{ print “Yes, Vanilla Coke exists!”; }
else
{ print “No, Vanilla Coke doesn’t exist”; }
Now, if you run this on your website or through the command prompt using the same %pop we made a minute ago, the ELSE is activated because we never made the key Vanilla Coke.

Like we discussed earlier, you can do whatever you want inside the {} brackets, all we did in the last two examples was print a little message to the screen. But what would we do if we wanted to see if a key exists, and if it does, delete it?

That’s simple:

my %pop = (
“Mello Yello” => “good”,
“Pepsi” => “nasty”,
“Mountain Dew” => “pure as gold”
);

if (exists $pop{‘Pepsi’})
{ delete $pop{‘Pepsi’}; }
else
{ print “No, Pepsi doesn’t exist”; }

That might be a little confusing at a first glance, as you can see we are using quite a few {} brackets. All we did was replace the print statement “Yes it exists” from the last example with the delete method as you learned earlier. If you run this script, it will find Pepsi and delete it for you.


Reversing Keys and Values

It has been said that you can’t consider yourself a hash expert unless you know how to remap your hash in such a way all your keys become values and all your values become keys. To be honest with you, I don’t see any logical reason anyone would do something like this and I have never used this before in my life.

my %names = (
“Bill” => “Nye”,
“Bart” => “Simpson”,
“Buffy” => “Slayer”
);

my %reversed_names = reverse %names;

foreach(keys %reversed_names)
{
print “$_ => $reversed_names{$_}\n”;
}

The new hash name can be whatever you want to call it, %reversed_names isn’t a built-in function. You could have called it %newhash and it would work exactly the same.

We first create a new hash and call it whatever you want, we then use the reverse command on the %hash we want to reverse the keys and values for. Since we are assigning the reversed hash to a different hash all together, the original is not affected.

After running that code in your window, the results will be something like:

Nye => Bill
Simpson => Bart
Slayer => Buffy

Notice how the first names are now following the last. The last names are now the keys and the first names were turned into the values.


The merging of hashes

Sometimes you will want to merge two or more different hashes into one large hash. This is done using a simple hash assignment.

my %bighash = (%hash1, %hash2);
%bighash now contains each key and value pair from both hash1 and hash2. Since hashes are not stored in any specific order (technically it is, Perl orders them in a way it can read them more efficiently. But for our sake, it’s pretty much random).

my %names1 = (
“Bill” => “Nye”,
“Bart” => “Simpson”,
“Buffy” => “Slayer”
);

my %names2 = (
“Fred” => “Flinstone”,
“Dino” => “Flinstone”,
“Xena” => “Princess”
);

my %newnames = (%names1, %names2);

The %newnames now contain all six key/value pairs like you would expect.

Sorting your hash

There is no way you can know which order your hashes will print in by default, and chances are when you’re messing with a fair amount of data you will want to sort them out in one fashion or another.

We can sort hashes alpha-numerically by using the sort method as we’ve seen in some of the earlier tutorials. The sort will iterate through each element in your list and put them in order by keys, this is very impressive when you can sort hundreds of thousands of element entries in a few seconds.

foreach (sort keys %hash)
{
….
}

We have to use the foreach looping structure again, this way perl can read every key/value pair that’s stored in our hash. Next we call sort on our keys from %hash. Think of it as saying “SORT the KEYS of %HASH” and it makes logical sense, it wouldn’t make sense saying “Keys the SORT of %HASH”. Hopefully that will help you remember which order they go in.

my %music = (
“Ride of your life” => “John Gregory”,
“Kiss Me” => “Sixpense None The Richer”,
“Superman” => “Five For Fighting”
);

foreach (sort keys %music)
{
print “$_ => $music{$_}\n”;
}

results:
Kiss Me => Sixpense None The Richer
Ride of your life => John Gregory
Superman => Five For Fighting

This will sort alphanumerically giving numerics first, meaning if any of your hash keys begin with a number, they’ll appear before the rest of them. But as you can see from the example I used used from the above, it alphabetized the names of the songs for me.

Sometimes you want to sort your hash backwards printing in reverse alpha-numeric order. We do this by using the reverse method on our sort block and Perl will rebuild the hash backwards for you.

foreach (reverse sort keys %hash)
{
….
}

The only difference between this and our last sort is the reverse which is called before sort. This also makes sense in English when read as “REVERSE the SORTED KEYS of %HASH”. Using the same example as we did with our songs above, this is how you would get them to print backwards according to key.

my %music = (
” Ride of your life” => “John Gregory”,
“Kiss Me” => “Sixpense None The Richer”,
“Superman” => “Five For Fighting”
);

foreach (reverse sort keys %music)
{
print “$_ => $music{$_}\n”;
}

results:
Superman => Five For Fighting
Ride of your life => John Gregory
Kiss Me => Sixpense None The Richer

As you can see our list was placed in reverse-alpha-numeric order for us. Try to memorize which order reverse, sort and keys go in. The order will always go REVERSE then SORT then KEYS then the hash.

Challenges

1) Without referring to the examples presented in this chapter, write your very own hash of names. Use the first name as they key and they last name as the value and create three key/value pairs.

One possible solution is:
————————————————————————
my %names = (
“Lucy” => “Lawless”,
“Kevin” => “Sorrbo”,
“Santa” => “Clause”
);
————————————————————————

2) Delete any key from the hash you made and insert a new key/value.

One possible solution is:
————————————————————————
my %names = (
“Lucy” => “Lawless”,
“Kevin” => “Sorrbo”,
“Santa” => “Clause”
);

delete $names{‘Kevin’};
$names{‘Tony’} = “Hawk”;
————————————————————————

3) Using the same hash, check to see if the name Steve exists as a key. If it doesn’t, print out a message saying it can’t be found.

One possible solution is:
————————————————————————
my %names = (
“Lucy” => “Lawless”,
“Kevin” => “Sorrbo”,
“Santa” => “Clause”
);

if (exists $names{‘Kevin’})
{ print “Kevin was found!”;}
else
{ print “The key Kevin wasn’t found”; }
————————————————————————

4) What is the error in this code?

foreach(keys sort %hash)
{
print “$_ => $hash{$_}\n”;
}
————————————————————————
The keys and sort are in the wrong order. The correct order would be foreach(sort keys %hash).
————————————————————————

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
0

Chapter 5 – Perl Arrays

-

Chapter 5 – Perl Arrays

An array is a list of elements and uses @ in its name. Unlike scalars where the variable can contain any amount of any one thing, an array can hold any amount of many things.  Arrays are lists of information tied together under a common name.


Array assignments/creation

Arrays are set up similar to scalars. Instead of using quotes on the assignment we use parenthesis.

my @numbers = (1, 2, 3);

If the array contains data other than numbers you will need to put quotes around each individual item in the array.

my @names = (“Sir Batman”, “Sir Robin”, “Sir Catwoman”);

There is another way to assign arrays to a list of one-word items. If everything in the array is going to be a single word, qw() allows you to assign a list of items without wrapping them in quotes.

my @names = qw(batman robin catwoman);

In the above, batman, robin and catwoman are each individual items in the array.

An array can be any length (as long as you have enough virtual memory to hold the data), but it wouldn’t make much sense using one value when instead a scalar would work just fine.


Printing arrays

There are a number of ways to print arrarys. The first way is identical to the way scalars are printed. The following would have an output of 123 and is the easiest way to print out everything in the array.  It is not very practical though as the output does not contain spacing.

my @numbers = (“1 “, “2 “, “3 “);
print @numbers;

One way of dumping out the array list with spaces in between is to wrap quotes around the array.  This is not done much in practice but it does produce an output of 1 2 3.

print “@numbers”;

A quick example at properly printing arrays with spaces is shown below. Joining and other advanced functions will be covered later in this chapter. It is placed here just as an example.

print join( ” “, sort @numbers);

Instead of printing out the entire array it is possible to print out very specific items. Using the @numbers variable about containing 1, 2, 3 the following would have an output of 2.

print $numbers[1];

Perl starts its numbering at 0 so when printing out arrays keep in mind the very first item in the array has an index of 0. In the example above the index 1 is actually the second item in the list (which is why the output is 2). Notice the $ scalar variable being used in the previous example. When dealing with a single value in an array list you reference it as a scalar. This sheds light on how arrays are handled in Perl. An array is a list of scalars. When called independently they are treated as scalars.

There is a trick to print out the last item in an array and it works if you have no idea how many items are in the array itself. $numbers[-1] gives access to the last item in the list. Note the last item is not [-0] as there is no such thing as a negative 0. Going backwards the numbering starts at -1.

print $numbers[-1];


More array assignments

To assign an array index a different value, simple use:

$numbers[3] = “4″;

Now our @numbers contains the numbers 1, 2, 3, 4. Our [3] represents the fourth digit (counting from zero as being one) and we added another number to our list. You could, for the sake of doing it, assign it so high it leaves all unused positions undefined.  This practice is not recommended.

$numbers[999999] = “5″;

The above would produce 999996 undefined values because the array had to build enough room for 9999999. Again, this shouldn’t be done for real life applications, but you can have fun with it and see how it affects the speed of your scripts.

Before we continue, here is an example of an assignment to an array that’s not solely number-based.

my @states = qq(Ohio Minnesota Nevada Oklahoma Michigan);

$states[4] = “Florida”;

@states now contains Ohio, Minnesota, Nevada, Oklahoma and Michigan.


Pop and Push

POP and PUSH are methods used to add or remove the last element of an array. If it was decided the last item in array was no longer needed it can be simply popped off.

my @numbers = (“1″, “2″, “3″);
pop(@numbers);

The above would remove 3 from the array permanently.  To check what item would be popped off before actually doing it, you could use something like the following.

my $lastnumber = pop(@numbers);
print $lastnumber;

Push is the counterpart of pop. Push allows you to add information to the end of an array.  The below example adds 3 back to the end of the @numbers array which was removed earlier in this section.

push(@numbers, “3″);

Regardless of how many items are in the array, push and pop will always work with the last item.
Shift and Unshift

Push and Pop work at the end of your list, similarly shift and unshift work at the beginning. Unshift is the opposite of push and adds an item to the beginning of the array.

unshift(@numbers, “0″);

The @numbers array now contains 0, 1, 2, 3. After adding the 0 it is decided maybe that wasn’t such a good idea. To remove the first item (which is now 0), simply:

shift(@numbers);

The @numbers array now contains 1, 2, 3 again.

Again, to check what the first item in the array is before shifting it off, you could do something like:

my $firstitem = shift(@numbers);
Reversing an array

Perl has a nice reverse feature allowing more control over the order of the array. Reversing an array will reverse the order of everything in the array permanently while printing a reverse only prints a reversed version of the array but it never actually changes the order of the items.

print (reverse @numbers);

Using the @numbers array, reversing the output would produce 321. As discussed earlier, this format isn’t very useful for every day applications. To print out a reversed array with spaces in between, simply:

print join(” “, reverse @numbers);

When sorting any list of information (arrays, hashes or any other data) during a print(), the original data will return to it’s original state after the print succeeded. The data is only sorted for the printout.

To permanently sort the variables, you could assign them to their reversed or sorted (as you’ll learn later) forms.

@numbers = reverse @numbers;
print @numbers;

Counting indexes or entries

$#array returns the total number of indexes in the array. This is a useful way in determining the last valid index in the array.

print $#numbers;

To print out the first or the last item in the @numbers array, simply:

print $numbers[0];      
print $numbers[-1];

If the concept of indexes is confusing, run the code from the bottom of this page called ‘indexes’ for further examples.

Scalar is a function that simplifies knowing how many items exist in an array. Scalar @numbers will contain the number 3 as there are 3 items currently in the list.

scalar @cookies;

Merging

Your company just merged with another firm down the street and you want one large list of employees rather than two separate lists. This can be a fairly common task and in Perl it’s quite simple to merge two or more arrays to combine one, larger array.

my @employees1 = (“Fred Flintstone”, “Barny Rubble”, “Dino Fintstone”);
my @employees2 = (“Wilma Flintson”, “Bamm-Bamm”, “Jigglypuff”);
my @allemployees = (@employees1, @employees2);

@allemployees now contains all the names from employees1 and employees2 with employees1′s data first. If you want the second set of employees to appear on top, all you have to do is change the assignment order to = (@employees2, @employees1);


Array splicing

Perl allows us to be able to remove (and optionally return) more than one element from an array at a time using splices. A splice takes a list, an offset and a length.

splice (@array, offset, length);

The offset is an integer where you want the splicing to begin. The length is also a whole number and this is the number of indexes to be spliced.

my @colors = (“red”, “blue”, “orange”, “purple”, “pink”, “white”);

splice(@colors, 0, 2);
print @colors;

We set the offset at 0, which is the 0 index red and the length of 2 . This will remove the first three sets of information from the list leaving purple, pink and white left. If we spliced (@colors, 2, 1), we would be removing the index[2] (orange). Since our length is only 1, we’re only removing one index.


Sorting

Printing a list of 100,000 names would be a mess if we couldn’t sort the list. You’d have names or phone numbers or dates in insertion order rather than a user-friendly alphabetical or numerical order. Luckily for us, Perl makes it simple for us to sort an entire list alphabetically.

my @animals = (“frog”, “toad”, “snake”, “grasshopper”, “bird”);
print join(” “, sort @animals);

sort(@animals) will take the array and put it in alpha-numerical order for you. Using sort(@animals), we would get back: bird, frog, grasshopper, snake, toad. If we had numbers (“1″, “3″, “5″) in with our animals, the numbers would print before the animals.


Deleting

Sometimes you will want to remove a certain element from a list. There are many ways to go about doing this. In this example we will be using delete which is no longer a fully-supported array command. Using this will not delete the array index but instead it will set it’s value to null/undefined.

When under use strict, you will run into complications if you use this method.

To remove a single piece of information we need to treat the list as a scalar.

my @animals = (“frog”, “toad”, “snake”);
delete $animals[0];

The above code will remove frog from the array since it is residing in the index 0.

If instead you wanted to delete an entire array, the quickest way would be to assign it a null value. A null value is different than an undefined value, so don’t try @animals = undef; thinking it’ll delete your array. Instead, use:

@animals = ();


Summary

Arrays can be a very useful way for you to reuse information from a list. You have learned how to create an array, read information from an entire set of values and how to pick apart just pieces of information. You have also learned how to merge more than one list together to form a single and larger list. Using the techniques we went over, you should now be able to determine how many indexes you have and know how to delete and/or store certain indexes into a new array all by itself.

Challenges:

1) Create an array @animals and randomly come up with half a dozen names. Be sure to put them in random order. Now take @animals and sort them in a reverse alphabetical order. Remember to be sure to have the elements print out with spaces between them.

One possible solution is shown below:
————————————————————————
my @animals = (“turtle”, “bumblebee”, “crab”, “ostriche”, “penguin”, “beetle”);
my @sorted_animals = (reverse sort @animals);
print “@sorted_animals”;
————————————————————————

2) Oops, we lost a few animals on our farm. The third and the fifth animal in your list ran away, better clear them from your inventory.

One possible solution is shown below:
————————————————————————
my @animals = (“turtle”, “bumblebee”, “crab”, “ostriche”, “penguin”, “beetle”);
delete $animals[4];
delete $animals[6];
————————————————————————

Complete scripts:

Understanding Array Indexing

#!/usr/bin/perl

use warnings;
use strict;

my @planets = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);

print “——————\n”;
print “Postive indexes\n”;
print “\@planets = (\”mercury\”, \”mars\”, \”earth\”, \”saturn\”, \”pluto\”, \”marsian’s homeland\”)”;
print “——————\n”;

my $count = “-1″;
foreach (@planets) {
$count++;
print “index[$count] = $_\n”;
}

print “\n\n”;
print “——————\n”;
print “Negative indexes\n”;
print “\@planets = (\”mercury\”, \”mars\”, \”earth\”, \”saturn\”, \”pluto\”, \”marsian’s homeland\”)”;
print “——————\n”;

my $countback = “0″;
foreach (reverse @planets) {
$countback–;
print “index[$countback] = $_\n”;
}

Understanding Pop/Push/Shift/Unshift

#!/usr/bin/perl

use warnings;
use strict;

my @planets1 = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);
my @planets2 = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);
my @planets3 = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);
my @planets4 = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);
my $elements = “mercury mars earth saturn pluto marian’s homeland”;

print “——————-\n”;
print “Before:\n”;
print ” $elements\n”;
print “Effect:\n”;
print ” POP\n”;
print “Results:\n”;

pop(@planets1);

print ” “;
print join(” “, @planets1);

print “\n——————-\n\n\n”;

print “——————-\n”;
print “Before:\n”;
print ” $elements\n”;
print “Effect:\n”;
print ” PUSH push(\@array, \”jupiter\”)\n”;
print “Results:\n”;

push(@planets2, “jupiter”);

print ” “;
print join(” “, @planets2);
print “\n——————-\n\n\n”;

print “\n——————-\n”;
print “Before:\n”;
print ” $elements\n”;
print “Effect:\n”;
print ” SHIFT\n”;
print “Results:\n”;

shift(@planets4);

print ” “;
print join(” “, @planets4);
print “\n——————-\n\n\n”;

print “\n——————-\n”;
print “Before:\n”;
print ” $elements\n”;
print “Effect:\n”;
print ” UNSHIFT unshift(\@array, \”sun\”)\n”;
print “Results:\n”;

unshift(@planets3, “sun”);

print ” “;
print join(” “, @planets3);
print “\n——————-\n\n\n”;

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
0

Chapter 4 – Perl Scalars

-

Chapter 4 – Perl Scalars

Scalars are the most fundamental variable or storage type used in Perl. Because of this, these are used more often than all the rest combined. Scalars can contain a single digit, a line of text, a paragraph of text or even an entire book. Although it can contain any length of data it can only contain ONE data. That is to say a scalar variable is a single piece of information.

$scalar = “”;

Scalars are defined using the symbol $ before its name. For example the following are all valid scalar names: $name, $state, $color. Variable names typically start with letters but can contain numbers and underscores throughout (ie: $first_name, $state2, $favorite_color).


Setting up your first scalar

To initialize variables in Perl, it is best practice to call it with my preceding the variable name. This makes the script a lot more secure and it will allow it to perform under strict.  Most programmers agree that Perl scripts should always be written under a strict environment to ensure security and integrity of data.  Variables are only initialized once and it has to be performed before attempting to use the variable.  In a way, initializing a variable tells Perl “Hey! We have a new variable we want you to be aware of!”.  Below is an example of initializing a scalar variable and assigning it a value of perl learner.

my $name = “perl learner”;

Here we are making the new scalar $name. name is the actual name of our variable, again this can be pretty much anything as long as it starts with a letter. Since this is the first time the variable $name is being used we need to call my to proceed it.

Why use variables? Placing data in a variable makes it simple, efficient and clean to reuse data an infinite number of times without having to rewrite it manually. By having your data stored in a variable you

Printing a scalar

Of the three variables you’ll be learning, scalars are the easiest in terms of creation and printing.

print $name;

In Perl, we use the command print to output something to the screen. It’s the same thing as echo in PHP. Any time you want to print a scalar, type in print $scalar_name.

For example, we’ll create a scalar and store our pet’s name inside and print it to screen:

my $pet = “molly”;
print $pet;

Using the above code the output on the screen should be molly.


Deleting a scalar value

Generally you don’t worry about deleting the contents of a scalar. If you don’t want to print it to screen or manipulate it into the rest of your program, simply leave it alone. If you truly wanted to delete it, you could assign its value to a null value “”.

$pet = “”;

This sets the value to null but it technically doesn’t delete it. The variable namespace is still in memory until the end of the Perl script. There is no way to literally delete a variable once it is created.


Copying a scalar

If you had a variable setup and you wanted to make a backup copy of it, simply assign one variable to the other.  For example:

my $name = “Batman”;
my $name_backup = $name;
print $name_backup;

The above example would produce the output of Batman. The $name_backup was assigned the value of the early created variable $name meaning it contains everything that $name does.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
0

Chapter 3 – Your First Perl Script

-

Chapter 3 – Your First Perl Script

In this section we will be going over the basics of setting up and running your first Perl script. Before we continue, if you have not installed Perl on your system, download the latest MSI version from http://www.activestate.com under ActivePerl.  This tutorial was written for Windows users but with minor changes it should work on Mac and Linux boxes as well.

On your desktop, right-click and select New>Text Document. Rename the file to test.pl and click enter. “.pl” is the Perl file extension. Perl files can also use the extension .cgi but that is typically reserved for Perl CGI scripts. Both work in either environment and it is not uncommon for programmers to use the .pl extension for web development.

The first line of every Perl script is called the shebang line. This line begins with the pound symbol and continues with the location of Perl on your system. If you are using Windows and did a default install of ActiveState Perl, your shebang will look like this:

        #!/usr/bin/perl

Okay, let’s begin your first Perl script. Double click on your test.pl file on your desktop to open it up in Notepad for editing. If it doesn’t open in notepad, right-click the file and click Edit. Perl files, by default, open in notepad for editing.

Type in the shebang line on the first line and click enter a few times. Then enter the following infamous Hello World! Shoutout.

print “Hello World!”;

To print in Perl, whether it be information to a database or to the screen, we call upon the print command. We usually use quotes around our content and end it with a semi-colon. Nearly ALL Perl lines will end in a semi-colon and it is one of the most common mistakes made- even with programmers who’ve used Perl for years. It’s very simple to forget something as little as a semicolon.

Click on File>Save to save your script. Open up your cmd or command prompt by click on your Start icon>Run> then type in ‘cmd’ if you are on Win 2000+ or type ‘command’ if you are on an older version of windows.

To run a Perl script from your desktop, you have to travel through the command prompt to your desktop directory. Once you’re in the Desktop directly in the command line, type in

            perl test.pl

The output of the script should be Hello World!. If you have successfully greeted the world, congratulations! You have written your first Perl script!

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)