April 2006


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.

General24 Apr 2006 02:12 pm

Opening a directory is just like opening a file. Though you will probably need to follow the full server path or symlinks to get to the directory you want. Suppose you want to open the "docs" directory, which on your server has the path "/home/username/www/docs/". You would do it like this:

CODE:
  1. opendir(IMD, "/home/username/www/docs/") || die("Cannot open directory");

Like a file we can make that path a variable and use it instead:

CODE:
  1. $getdir="/home/username/www/docs/";
  2. opendir(IMD, $dirtoget) || die("Cannot open directory");

Now that it is open, we will want to read in the contents.

Read the Contents

The contents of the directory will be the file name of each file in the directory, including "." and ".." in the list. You'll want to toss those two out if you want just the files themselves. To read the directory, we can read the contents into an array and use the array:

CODE:
  1. @thefiles= readdir(IMD);

Use the handle you assigned to your directory in the readdir command. In our case, it is IMD. Now the contents of the images directory are in the @thefiles array.

Close the Directory

CODE:
  1. closedir(IMD);

The whole bit from open to close looks like this:

CODE:
  1. $getdir="/home/username/www/docs/";
  2. opendir(IMD, $dirtoget) || die("Cannot open directory");
  3. @thefiles= readdir(IMD);
  4. closedir(IMD);

You can use this to list the files in a directory, though not elegant as using regular expressions, it will will serve.

CODE:
  1. #!/usr/bin/perl
  2.  
  3. $getdir="/home/username/www/docs/";
  4. opendir(IMD, $dirtoget) || die("Cannot open directory");
  5. @thefiles= readdir(IMD);
  6. closedir(IMD);
  7.  
  8. print "Content-type: text/html\n\n";
  9. print "<html><body>";
  10.  
  11. foreach $f (@thefiles)
  12. {
  13.   unless ( ($f eq ".") || ($f eq "..") )
  14.   {
  15.    print "$f<br />";
  16.   }
  17. }
  18.  
  19. print "</body></html>";

This can be used as an easy way if displaying multiple items like images instead of writing a bunch of HTML code for each image, especially if their are a lot of files, handy if you are lazy or it happens to be Tuesday.

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. }

PHP Code21 Apr 2006 07:04 pm

Retrieving last modified timestamp for a file

CODE:
  1. <?php
  2. //set path/filename or passed from form argument
  3. $filename = '/path/filename.dat';
  4. // checks that the file actually exists and queries the last modified timestamp
  5. if (file_exists($filename)) {
  6.         echo "$filename exists";
  7.         echo " last timestamp: " . date("d-m-y", filemtime($filename));
  8. } else {
  9.         echo "$filename does not exist";
  10. }
  11. ?>

« Previous PageNext Page »


Web Advertising - Xbox Mod Chips - Loans - Credit Card Consolidation - Mortgage
X10 Home Security|Dakar's Photos
Listed on BlogShares