PERL code snippets


PERL code snippets24 Apr 2006 02:50 pm

Define an Array

An array is defined in perl as;

@arrayname = ("element1", "element2");

The array name begins with an "@" symbol. This is how Perl know it is an array and not something else. You can have as many elements as you need, I just listed two above to keep from running on. The elements can be numbers or strings depending on what you need. If you use plain numbers, the string quotes wouldn't be needed here, for example:

CODE:
  1. @one_two_three = (1, 2, 3);

This would define an array named @one_two_three with three elements: the numbers 1, 2, and 3. Since the elements are only numbers, they need no quotes around them. On the other hand, if you wanted an array of string values, you'll need the quotes so the interpreter sees the elements as strings:

CODE:
  1. @browser = ("NS", "IE", "Opera");

This time we have an array named @browser with three string elements: NS, IE and Opera. The question now is how do we make use of these elements later?

How to Access Array Elements

Suppose we wanted to grab the element "IE" out of the browser array above. You'll notice "IE" is the second element in the array, but look at the code we will use to get it carefully:

CODE:
  1. $browser[1]

You'll see that we get the element by using a regular variable (the $ sign) with the same name as the array (browser). Then we use brackets with a number to get to a certain element within the array. Each array is ordered, but not starting at the number one like we would like. Arrays instead begin ordering at the number zero! So, the first element of an array is always accessed using:

CODE:
  1. $arrayname[0]

So, this is why we used $browser[1] to get "IE" above. It is the second element, but its list number is 1. So, be sure to remember this when working with arrays. They start the number list at zero, so be careful when you try to get an element or you might have a hard time figuring out where things went wrong in your script (believe me, I have done this a few times).

In a similar way, we can get the other elements for the array and use them. Let's say we wanted to write a little sentence about the browsers. We could use the array elements as part of the sentence:

CODE:
  1. print "I like to use $browser[0], $browser[1], and sometimes $browser[2].";

Yes, a pretty simple sentence indeed- but here is the result:

I like to use NS, IE, and sometimes Opera.

Not much more useful to us than 3 variables. But if you use a loop, an array can be very useful either to save typing or to manipulate a set of similar values.

Arrays and Loops

This is where an array can be more powerful, if you want to print the three browser names you could now use a loop rather than a separate print line with variable names. This is really handy if the list is a long one, but to keep things short we'll stick to our three element browser array. The following could be used to print the three browser names, one per line:

CODE:
  1. @browser = ("NS", "IE", "Opera");
  2.  
  3. print "My Favorite Browsers List:\n\n";
  4.  
  5. foreach $browser (@browser)
  6. {
  7.  print "$browser\n";
  8. }

Notice how we used the foreach loop we looked at in the last section. As you can see, it is very handy with arrays. It loops through enough times to grab each element in @browser and print it. Also, using the foreach loop, we didn't have to add the brackets to access the array element. You'll notice we just used $browser inside the loop. This is because the foreach loop knows which elements to grab- all of them. So it gives back the next element in order each time.

PERL code snippets24 Apr 2006 02:43 pm

The for Loop

A for loop takes the loop the number of times defined.
Here is the general form of a for loop:

for (starting assignment; test condition; increment)
{
code to repeat
}

Well, that's great, but it doesn't tell us much about what happens. Instead, let's make a statement, "Linux Rocks" 10 times using a for loop like this:

CODE:
  1. for ($count=1; $count<11; $count++)
  2. {
  3.  print "Linux Rocks!\n";
  4. }

You'll notice above we created a variable named $count to test the condition each time through. In this case, we only used it to test the condition and not inside the loop itself. The first time through $count is 1 since we have that as our starting condition. The loop will keep repeating until count finishes the 10th time through. When it tries to go through as 11, it is stopped because it fails the test condition- 11 is not less than 11. So, what we get is this repetitive list:

Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!
Linux Rocks!

You could also use the $count variable inside the for loop to change what is printed. This comes in handy when we get to arrays, but for now we will just print the value of $count each time through. This will print a list of numbers from 1 to ten:

CODE:
  1. for ($count=1; $count<11; $count++)
  2. {
  3.  print "$count\n";
  4. }

Now you will get this:

1
2
3
4
5
6
7
8
9
10

The while Loop

The while loop repeats a portion of code, but it reapeats it until the condition you provide comes back false. Here is the general syntax for the while loop:

while (test condition)
{
code to repeat
}

So, we could print out that list of numbers from one to ten with the while loop instead. Be sure to define your test variable (in our case $count) before the loop begins. You will also need to be sure to increment the test variable inside the loop. Here is the code for the number list with a while loop:

CODE:
  1. $count=1;
  2.  
  3. while ($count<11)
  4. {
  5.  print "$count\n";
  6.  $count++;
  7. }

For some things, this is easier to use than the for loop. It just depends on what action you wish to perform.

The foreach Loop

The foreach loop is one that is almost always used with some sort of array. We will have more use for it later. If you have an understanding of arrays, this will make a bit more sense:

CODE:
  1. foreach variable_name (array_name)
  2. {
  3.  code to repeat
  4.  }

An array is a way of storing a group of variables that makes them easy to access and manipulate later. The foreach loop takes each element of the array and operates on it with your code. Let's say we had an array named @bank (The @ sign signals an array). Using the foreach loop, we could print out each element of the array. If we use the variable $dollar to represent an element in the array, we could print out every $dollar we have in the @bank, so to speak!

CODE:
  1. foreach $dollar (@bank)
  2. {
  3.  print "$dollar\n";
  4. }

PERL code snippets24 Apr 2006 02:36 pm

The if Condition

The if condition lets you check to see if a statement is true using a comparison operator. If the statement is true, the next block of code between the curly braces {} will be executed, else perl moves on to the eht next command.

sample if statement:

CODE:
  1. $mbytes=5;
  2.  
  3. if ($mbytes <10)
  4.  {
  5.    print "Not much space for storage";
  6.  }
  7.  
  8. print "Plenty of free space remaining.";

This checks to see if the variable $bytes is less than 10. If true, it executes the statement inside the braces, and then goes on. If not, it will go straight to the print statement after the braces. If $mbytes being 5, it prints this result:

Not much space for storage
Plenty of free space remaining.

If the $mbytes variable were equal to 20, it would skip the code inside the braces and just print the last line:

Plenty of free space remaining.

Using else and elsif

You can also make the script do something if the "if" condition is not true. If you have just one other option, simply use and else statement after the if statement, like this:

CODE:
  1. if ($mbytes <10)
  2.  {
  3.    print "Not much space for storage";
  4.  }
  5. else
  6.  {
  7.   print "Free space getting limited.";
  8.  }
  9.  
  10. print "Enough free space for now.";

Now, if $mbytes is less than 10, the program gives you:

Not much space for storage
Free space getting limited.

However, if $mbytes is anything greater than 10, it will bypass the statement in the first set of braces and execute the code within the else statement braces. It would print this:

Not much space for storage
Enough free space for now

If you want to check for a couple of conditions, you can use elsif to do another check and leave the else code as a last resort. You can have as many elsif statements as you want, but keep them between the if and the else statements. Here is a sample:

CODE:
  1. if (($mbytes <10) && ($mbytes> 0))
  2.  {
  3.    print "There is enough free space";
  4.  }
  5. elsif ($mbytes <= 0)
  6.  {
  7.   print "You need more free space!";
  8.  }
  9. else
  10.  {
  11.   print "Enough free space for now.";
  12.  }
  13.  
  14. print "Free space is getting limited.";

You'll notice the && operator here, it checks to see that two conditions are true before it will return true. So, for the first bit of code to execute, $mbytes must be between 1 and 9. Also, note the extra parentheses, they separate the condition from the comparisons within it.

Now, if $mbytes is between 1 and 9, you get:

There is enough free space
Free space is getting limited.

However, if $mbytes is zero or less, you get:

You need more free space!
Free space is getting limited.

Finally, if $mbytes is 10 or more you get:

Enough free space for now
Freespace is getting limited.

You could check for several ranges here and get smart with the people using the program. Just keep using the elsif statement to check for more ranges.

Using unless

The unless condition checks for a certain condition and executes it every time unless the condition is true. Sort of like the opposite of the if statement:

CODE:
  1. unless ($mbytes == 10)
  2.  {
  3.   print "Exactly 10mbytes free space remaining.";
  4.  }

This shows the message every time unless $mbytes is actually equal to 10. It's a handy shortcut for a longer if/else statement.

PERL code snippets24 Apr 2006 01:57 pm

To determine a file's existence

# check if file exists:

CODE:
  1. if (-e "filename.txt")
  2. {
  3.   #next action
  4. }

-e = existance
Filename could also be a variable as in this example

CODE:
  1. $filename="test.cgi";
  2. if (-e $filename)
  3. {
  4.   #next action
  5. }

Other switches;

File exists, has a size of zero: -z
File exists, has non-zero size: -s
Readable: -r
Writable: -w
Executable: -x

So, if we want to check whether we can read a file before we try to open it, we could do this:

CODE:
  1. $filename="test.cgi";
  2. if (-r $filename)
  3. {
  4.   #next action
  5. }

Text File: -T
Binary File: -B

They work in the same fasion
Multiple Tests

You can test for two or more things at a time using the "and" (&&) or the "or" ( || ) operators. So, if you want to know if a file exists and is readable before opening it, you could do this:

CODE:
  1. $filename="test.cgi";
  2. if ( (-e $filename) && (-r $filename) )
  3. {
  4.   #next action
  5. }

« Previous Page


Bad Credit Mortgages - Cheap Magazines - Adverse Credit Remortgage - Internet Advertising - Loans
X10 Home Security|Dakar's Photos
Listed on BlogShares