Applications

Fun and Games

Personal

Pictures

Tutorials

Forum

Main

This is the basics of Perl.

This is quick look at perl and some references you should know and some scripts.

Contents:

Basics(Starting out, variables, operations, etc)
Running Perl as webpages
Expressions / Matching (what is that symbol for?)
More on Arrays
Functions
Loops
Splicing
Running System Commands

Basics

Where can you get Perl? Perl is free cpan.org

Some of the basics about perl. Perl extensions are .pl and .pm, like HTML files/pages are .html.
The first line in your perl file needs to point to the directory in which perl is installed, so it can do the run time compile and actually run. The usual for this is either:

If running on Linux:

#!/usr/bin/perl

If running on Win32:

#!C:\Perl\bin\Perl.exe

Scalar Variables - holds a single value, string or number starts with $

Arrays - hold lists, starts with @

@myarray("Key1", "value1", "Key2", "value2");
so $myarray[0]=Key1....notice the $ not @ to get the value
$myarray[-1] is that last element in the array
$#myarray is the index of the last element in the array

Hashes (perfect)- hold elements with Keys and values, starts with a %

%myhash=@myarray;
so now
Key       Value
Key1 =>   value1
Key2 =>   value2
chomp, you will most likely be pulling some input in, you will pretty much want to chomp everything you take in. This will remove extra spaces, carriage returns, line feeds and junk.
print "give me some input";
$response = ;
chomp $response;

Running Perl in webpages

If you ftp something from windows to unix run and the perl code runs fine via command line, but you have issues (error 500) when trying to see the webpage run the dos2unix filename command.


If you want to run something in perl with the browser/webpage, you need to tell perl. So you need the following line in there before you start printing out what you are expecting to see on the page.

print "Content-type: text/html\n\n";

This tells perl that the information is html and will run in a webbrowser.

Most likely if you are going to run perl in a webpage you will be passing it information from an html page. Here is a quick few lines to parse the information out of a post or get from the HTML form to be used in the format of "$FORM{'variable'}";

$stuff = <STDIN>;
$holdme = $stuff;
print "Content-type: text/html\n\n";

@fields = split(/&/,$stuff);

foreach $field (@fields) {
	($name, $value) = split(/=/, $field);
	$value =~ tr/+/ /;
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

	#stop people from using subshells to execute commands
	$value =~ s/~!/ ~!/g;
	$FORM{$name} = $value;
}

Expressions (what does that mean?)

m// is matching operator

(=~) is a bind
with the 2 above you can pretty much match anything using perl
if($word=~m/ch/){print "this word would contain a ch.\n";}

qualifiers for matching
Qualifier Use Example
. Any character except \n /M.rk/ matches Mark but would not match Maark. There is more then 1 character between the M and r. To match a . itself use \./3\.14/ matches 3.14159.
* Zero or more of the previous item /M*rk/ Does not match Mark but would match ark, aaark, bark.
+ One or more of the previous item /M*rk/ Matches Mark,MMark, Not ark, bark.
? Zero or one of the previous item /M?ark/ Would match ark, Mark only.
| Alternative /Mark (and|or) Alan/ Matches Mark and Alan OR Mark or Alan
() Groupings /(Mark)+/ Matches Mark, MarkMark, MarkMarkMark, etc.
^ Anchor and match beginning of a String /^Mark/ Matches Mark was here, but not Here was Mark
$ Anchor and match end of a String /$Mark/ Matches Here was Mark, but not Mark was here
\b Match word boundry /\bbob\b/ Matches bob, not bobby or joebob
\B Match NOT a word boundary /\Bbob\B/ Matches bob in the middle of a word only, like joebobbill
[ ] Character class is a list of possible values inside brackets /[0-9]+/ matches strings with all numbers. A ^ inside the brackets negates whatever's inside /[^abc]/ matches anything except a,b,c
NOTE: Some Character classes are used so often, they have shortcuts:

\d  digit[0-9]
\w  word character [A-Za-z0-9]
\s  whitespace [\f\t\n\r]
[^\d] [^\w] [^\s] or \D \W \S - negating the shortcuts
More info can be found at: troubleshooters.com

Arrays

The following is a piece of code that will bring in a file and put each line of the file into an array. It will then check each line for a matching string. If the string is there it will print the next 5 lines.
open FH, File_I_Want_To_Read or die "Failed to open file";
@lines = ;
foreach $line (@lines){ 
  if ($line =~ m/String_to_Match/){
    $Counter = 0;
    print "After this will be the 5 lines";
  }
  if ($Counter < 6) { print $line; }
}
 

Functions

Calling functions:
This will look for a system function if there is not one locally.
myfunction();
sub myfunction { blah blah }

This will look for the local function
&myfunction;
sub myfunction { blah blah }

if you have the funtion you want to use stored in a variable you can do a:
&$myfunction;
sub myfunction { blah blah }




Loops

If you want to break out of a loop use last To continue use next

Splicing

print @lines[$start..$start+6];
This will print an array from $line[$start] to $line[$start+6]

Running system tools/commands

In order to run some operating system commands you need to use back ticks like to get the OS of a machine or machine name do the following:
chomp($OS = `uname` );  #Get OS...Linux, AIX, HP, etc
chomp($NAME = `uname -n`) #Get machine name, hostname
If you want to use a file use an easy the following commands:
open (FH, ">File.txt"); 
or
open (FH, ">>File.txt"); 
The filehandle (FH) will be whatever you use to reference that file in the future. > will rewrite the file >> will append to the file The close the file with the following.
close FH;
If you want to pull files from a directory you are in, say all the .jpg files, use glob to pull them in an array.
@Pics=glob "*.jpg";
If you want to pull picture files from a directory and rename them you can use the following routine.
@Pics=glob "*.jpg";
$i=1;
foreach $Pic(@Pic){
   rename $Pic,($i).".jpg";
   $i++;
}

Executing command line

At times you will need to run a command from the command line and get the output you can do that with :

$output = `command`;
For my phototool I use the following section of code to run a thumbnail generator
$source = "\"C:\\Documents and Settings\\markparz\\Desktop\\My 
Stuff\\Perl\\PhotoTool\\test\\*.jpg\"";
$des = "\"C:\\Documents and Settings\\markparz\\Desktop\\My 
Stuff\\Perl\\PhotoTool\\thumb\"";
$EZ = "\"C:\\Program Files\\Easy Thumbnails\\EzThumbs.exe\" $source 
/D=$des ";


print "Getting files from " . $source . "\n";
print "sending them to " . $des . "\n";
print "using command " . $EZ;
system($EZ);
Notice you have to escape the quotes, and slashes. The system($EZ) actually executes the command.

If you want to execute a command and have the program exit, substitute exec with system.