To run a perl script, just make sure it is executable and readable
(chmod u+rx scriptname) and then run it (./scriptname).
All perl scripts start with
#!/usr/bin/perl -w
(the -w is optional and
turns warning on, but there is no reason not to use it).
The next line is usually:
use strict;
This is not necessary,
but forces you to write cleaner programs and is a real good idea.
After the first line, all line MUST end with a semicolon.
To write something to the screen:
print "Hello World\n";
The \n means print a newline.
All scalar variable names in perl start with a dollar sign. All array names start with an ampersand (@). Unlike many other languages, there is no difference between integers, floating point numbers, or strings. The first time you use a variable in a program, you need to put the word "my" in front of it to declare it. But, you may declare a variable in any part of a program. The equal sign is used to give a variable a value. If a variable has a numeric value, you may do math (+,-,*,/) on it. Also, individual elements of an array (@array) are handled as scalar varibles ($array[1] for example). Arrays grow and shrink as needed. For any array, there is a special variable ($#array) which is the current size of the array.
Of course, a programming language must be able to do things multiple
times. This is where loops come in. A for loop is done as:
my $i;
for($i=0;$i<=10;$i++)
{
print "$i\n";
}
Often, one needs to run another program from perl. This can be done
with the system command.
system "ls";
If you want to use the output of the command in your script you
can use:
my $computer=`hostname`;
Instead of the system command, we used the backtick (the
apostrophe like thing below the tilda (~) on most keyboards). Now
$computer will have the output of the hostname command.
The chomp command (chomp($variable)); removes a single newline at the
end of a variable. Sounds dumb, but it is very useful.
A good way to get input from the keyboard is with:
chomp($input=<STDIN>);
Also useful is glob, which is similar to wildcards in the shell, e.g.;
my $JPG=glob "*.jpg";
Although what we covered is basically enough to do whatever you could
do with shell scripting, we haven't touched on the best features of Perl:
regular expressions and text processing. For these, check the
resources mentioned before.
This file contains everything we talked about
above (and a little more).