Perl How To


Below you will find short snipplets of code that I often refer to. I have found that these are useful to me and hopefully others will also find them useful. If you wish to contribute to this page send me an email sam@jswatson.com include a description of the code and an example. Thanks.

Change the working directory that the program uses
Determine the working directory that the program uses
Determine if the first character of a string is a set character



How to change/determine the working direcory
To find, change or determine the current working directory two perl functions must be used. First the "use Cwd;" must be used (preferably near the beginning of the program). Note: The "use Cwd;" only needs to be entered once reguardless of how many times it is refered to in the program. The second command will either the "cwd$quot; (check the working directory) or the "chdir" (change the working directory).
Example:

use Cwd;

print "Yourcurrent directory is", cwd, "\n";
chdir "/tmp" or warn "Directory /tmp not accessible: $!";
print "You are now in : ", cwd, "\n";

Check if the first character of a string is a set character
Sometimes you need to determine if the first character of a string is a set character. I use this when I accept an argument with the program name. Often I am looking for the "-" character so that I can apply an option.
Example: - looking for the dash (-) as the first character and the letter "h"

if ($#ARGV >= 0) {        # Was something provided with the program name
    $cha=$ARGV[0];        # Get the first ARGV
    if ($cha =~ / \A-/) {      # Check if it is an option (-)
        if ($cha =~ /h/) {      # Check for the letter h (help)
            HELP;                  # Execute the help subroutine
            exit (0);
         }
      }
  }