Perl Information Center Mini-Tutorial
Speakers know the advice of "Tell them what you're going to tell them ...",
which is what this very short mini-tutorial does. It's a preview of the
full tutorial provided at this site, with all the fat (and some of the meat) cut out. There's
no discussion - just notes and comments.
It's an introduction for newbies to get a sense of Perl in one reading,
although some sections may not make much sense until you've read the corresponding
tutorial. And for those of you coming back to Perl after an absence,
it's a reminder of what Perl offers and perhaps what you forgot.
A Simple Program
Just to get you started, here's a quick look at a traditional "Hello World" program.
#!/usr/bin/perl # this line required in Unix, optional on PCs
$name="Hello World"; # assigns a string value to the variable $name
print $name; # prints the variable $name to the screen
Executing a Perl Script Locally
To run the script on a local PC just save it to a file, such as "myscript.pl",
then type in:
perl myscript.pl # explicitly uses the compiler "perl.exe"
or
myscript.pl # Perl installation set PATH to point to perl.exe
Any filename can be used but .pl and .cgi are commonly used extensions.
Syntax
lines end in semicolon print "Hello" ;
comments are allowed # comments follow pound sign
single & double quotes are used print "Hello"; print 'Hello';
"" quotes interpolate variables $a="Hello"; print "$a";
"" quotes interpolate spec char print "Line 1 \n Line 2";
function parentheses are optional print("Hello"); print "Hello";
special quote characters \n \' \" \\ \t \f
BLOCK { } curly brackets define a BLOCK of code
EXPR ( ) parentheses define Expressions
whitespace is ignored, except inside quotes
' ' single quotes do not interpolate
( ) enclose a list
Operators
Arithmetic + - * / % = ++ --
Compound += -= *= /= %= **= x= .=
Numeric Compare == != < > <= >= <=>
String compare eq ne lt gt le ge cmp
Boolean and or not xor
higher precedence & | ^ !
short-circuit && ||
string . (concat) x (multiply)
range operator ..
matching / / operates on $_ by default
substitution s/ / / s/foo/bar/ replaces foo with bar in $_
bind scalar =~ operates on $_ by default
file I/O <> read amount depends on context
0, "0", '', (), undef are all false. all other values are true.
q/ / same as single quotes, no interpolation except \' and \\
qq/ / same as double quotes, interpolation
qx/ / same as backquotes, interpolation
qw/ / creates list of words separated by whitespace
Variables
variable types: scalar, array, hash.
Can use 'my' for declaration, but declaration is not required.
scalars can be strings, integers, floating point.
array elements are designated by []
hash elements are designated by {}
arrays are zero-based, elements can be any scalar type
scalar: my $x; # declaration is not required, but is allowed
$x = 5
$x = "Hello"
array: @x = (3,6,9) # $x[1]=3 $x[2]=6 $x[3]=9
@x = (3,"dog",4.5) # $x[1]=3 $x[2]="dog" $x[3]=4.5
@newarray = @x[0,1] # 2 elements from existing array
@newarray = @x[0..3] # 3 elements from existing array
($var1, $var2) = @x # $var1 = 3 $var2="dog"
@sortedarray = sort @x
@reversearray = reverse @x
$number = @arrayname #number array elements
$lastindex = $#arrayname #index of last element in an array
hash: %x = ("a",1,"b",2,"c",3) # $x{"a"}=1 $x{"b"}=2 $x{"c"}=3
%x = ("a"=>1,"b"=>2,"c"=>,3) # $x{"a"}=1 $x{"b"}=2 $x{"c"}=3
@keylist = keys %x # get list of hash keys
@values = values %x # get list of hash values
Special Pre-Defined Variables (hundreds exists- here are a few)
scalars $_ function default
arrays @ARG commandline
@_ subroutine arguments
hashes %ENV environmental variables
Variable Scope
variable scope is global by default. variables in the main script and
in subroutines are accessible everywhere. used 'my' to define scope.
$var = "value" global
my $var = "value" scoped to block where defined
Enforces scope use strict;
Flow Control
if (expression) {..statements..}
unless (expression) {..statements..} #same as if (!expression)
while (expression) {..statements..}
until (expression) {..statements..}
{..statements..} if (expression)
{..statements..} unless (expression)
{..statements..} while (expression)
{..statements..} until (expression)
if (expression) {...}
elsif (expression) {...}
else {...}
for ( initvalue; test; increment) {...}
for ($i=0; $i <= $max; $i++) {...}
foreach $var (list) {...} # list members put in $var
foreach (list) {...} # list members put in $_
(expression) ? (..true statements..) : (..false statements..)
Loop redirection: redo/next/last/line/continue
Subroutines
sub subname {
...statements;
return $result; #optional
}
subroutine arguments not predefined
call subroutines with any number arguments
arguments placed in @_ array, available within subroutine
To access @_ :
($logmessage, $priority) = @_; # common
$logmessage = $_[0]; # uncommon, and ugly
$logmessage = shift; # shift operates on @_
Functions (commonly used, built-in functions)
Strings lc, lcfirst, uc, ucfirst # capitalize
chomp, chop # truncate
index, rindex, split, subst # find/replace
chr, ord, length, reverse, sprintf # conversion/format
Numeric atan2, cos, sin # trig
exp, log, sqrt # logarithms
abs, hex, int, oct # conversions
rand, srand # random
Arrays push, unshift # add elements
pop, shift # delete elements
splice, split, join # combine/split
sort, reverse # rearrange
Hashes keys, values, each # access elements
delete, exists # delete/test
Files open, close # open/close
eof, getc, read, seek, tell # random access
chmod, unlink, rename, stat, truncate # modify
print, printf, write, format # print
Processes sleep, wait # timers
exec, system # run external processes
Time gmtime, localtime, time, times
Date/Time Function Reference
$result = time # seconds since Jan 1, 1970
($s, $m, $h, $mon, $yr $wdy, $ydy, $isdate) = localtime(time);
$year += 1900; # $year is # years since 1900
$now = localtime; # gets "Thu Oct 13 04:54:34 1994"
Files
open(INFILE, "input.txt") close INFILE;
open(OUTFILE, ">output.txt") close OUTFILE;
open(LOGFILE, ">>append.txt") close LOGFILE;
read 1 line of file using scalar $line = <INFILE>;
read all lines into array @lines = <INFILE>;
Read all lines into scalar: $/=undef;$var = <INFILE>;
Read specific lines into array: @all[0..5] = <INFILE>;
Write one line of text into file print DEST $text
Write array into file print DEST @array
print uses filehandle print FILEHANDLE $record;
CGI
Web page link to execute CGI script via link
<a href="myscript.pl">Execute a Script</a>
Web page with form to send values to CGI script on server
<html>
<body>
<h2>My Web Page</h2>
Contains one of each type of form element.
<form action="sample.pl" method="GET">
<input type="text" name="txt" >
<p>
<input type="submit" value="Submit">
</form>
</body>
</html>
CGI script - returns a simple web page
#!/usr/bin/perl
$return="Success"
print <<stop_html ;
Content-type: text/html\n\n
<html>
<body>
$return # Perl puts value of $return here
</body>
</html>
stop_html # no trailing whitespace allowed!
CGI script - sends existing page back to a user
#!/usr/bin/perl
# put any Perl script here that you want
print "Location: http://www.garybeene.com/index.htm" ;
CGI script - get form variables from QUERY_STRING
if ($ENV{'REQUEST_METHOD'} eq "GET") {
$qstring = $ENV{'QUERY_STRING'};
} else {
$qstring = read(STDIN, $qstring,
$ENV{'CONTENT_LENGTH'});
}
@pairs = split(/&/, $qstring); # splits name-value pairs
foreach $pair (@pairs) # loop through each pair
{
($name, $value) = split(/=/, $pair);
# Create a Name/Value pair set
$value =~ tr/+/ /;
# change + signs to spaces
$value =~ s/%(..)/pack("c",hex($1))/ge;
# convert the URI code
$in{$name} = $value;
# put form values in in hash array %in
}
print %in
CGI script - counter File
#!/usr/bin/perl
open (COUNTER, "+< counter.txt"); # read/write
$count = <COUNTER>; # read 1st line
$count++; # increment counter
seek (COUNTER,0,0) # go to start of file
print COUNTER $count; # save counter
close COUNTER; # close file
Regular Expressions
match / / operates on $_ by default
substitute s/foo/bar/ replace foo w/bar in $_
bind scalar =~ operates on $_ by default
capture match /( )/ captures results in $1, $2,
if (/foo/) {...}
if ($a =~ /foo/) {...}
RegEx expressions elements:
^ start of string \d a digit (0-9)
$ end of string \D a non-digit
. single character
\s whitespace \w (a-z, A-Z, 0-9, _)
\S non-whitespace \W not (a-z, A-Z, 0-9, _)
[aeiou] matches a single char from set
[^aeiou] matches a single char outside set
(foo|bar|baz) matches any specified alternatives
Quantifiers specify how many of the previous thing
* zero or more {3} matches exactly 3
+ one or more {3,6} matches between 3 and 6
? zero or one {3,} matches 3 or more
/^\d+/ string starts with one or more digits
If you have any suggestions for additions to this mini-tutorial, please let me know.
|