Introduction To Perl Programming
Introduction To Perl Programming
( perl 5 )
Contents
Basics
Variables and Operators
Branching
Looping
File Test Operators
Regular Expressions
Input and Output
Processing files mentioned on the Command line
Get Filenames
Pipe input and ouput from/to Unix Commands
Execute Unix Commands
The Perl built-in Functions
Subroutines
Some of the special Variables
Forking
Building Pipes for forked Children
Building a Socket Connecting to another Computer
Get User and Network Information
Arithmetics
Formatting Output with "format"
Commandline Switches
Basics
Scripts
Perl is a script language, which is compiled each time before running. That unix knows
that it is a perl script there must be the following header at the topline of every perl script:
#!/usr/bin/perl where the path to perl has to be correct and the line must not exeed 32
charachters.
Quotations
Single quote: '' or: q//
Double quote: "" or: qq//
Quote for execution: `` or: qx//
Quote a list of words: ('term1','term2','term3') or: qw/term1 term2 term3/
Quote a quoted string: qq/"$name" is $name/;
Quote something wich contains "/": qq!/usr/bin/$file is readdy!;
A subroutine can return lists and not only scalars like in C. Or an array gives the number
of elements in a scalar context and the elements itself in a list context.
Scalars
Fill in a scalar with: $price = 300; $name = "JOHN"; Calculate with it like: $price *=
2; $price = $oldprice * 4; $count++; $worth--; Print out the value of a scalar with:
print $price,"\n";
Arrays
Fill in a value: $arr[0] = "Fred"; $arr[1] = "John"; Print out this array: print join('
',@arr),"\n";
If two dimensional: $arr[0][0] = 5; $arr[0][1] = 7;
Assignments
Put something into a variable with a "=" or with some combined operator which assigns
and does something at the same time:
Comparisons
Compare strings with: eq ne like in: $name eq "mary".
Compare numbers with: == != >= <= <=> like in: $price == 400.
And/Or/Not
Acct on success or failure of an expression: $yes or die; means exit if $yes is not set.
For AND we have: && and "and" and for OR we have: || or "or". Not is "!" or "not".
Branching
if
if(condition){
command;
}elsif(condition){
command;
}else{
command;
}
command if condition;
Looping
while
while(condition){
command;
}
until(condition){
command;
next if condition;
command;
}
until(condition){
command;
last if condition;
}
until(condition){
command;
continue if condition;
command;
}continue{
command;
}
for (=foreach)
# Iterate over @data and have each value in $_
for(@data){
print $_,"\n";
}
map
# syntax
map (command,list);
map {comm1;comm2;comm3;} list;
# example
map (rename($_,lc($_),<*>);
Regular Expressions
What it is
A regular expression is an abstract formulation of a string. Usually one has a search
pattern and a match which is the found string. There is also a replacement for the match,
if a substitution is made.
Patterns
A pattern stands for either one, any number, several, a particular number or none cases of
a character or a character-set given literally, abstractly or octaly.
PATTERN MATCH
. any character (dot)
.* any number on any character (dot asterix)
a* the maximum of consecutive a's
a*? the minimum of consecutive a's
.? one or none of any characters
.+ one or more of any character
.{3,7} three up to seven of any characters, but as many as possible
.{3,7}? three up to seven, but the fewest number possible
.{3,} at least 3 of any character
.{3} exactly 3 times any character
[ab] a or b
[^ab] not a and also not b
[a-z] any of a through z
^a
a at beginning of string
\Aa
a$
a at end of string
a\Z
A|bb|CCC A or bb or CCC
tele(f|ph)one telefone or telephone
\w A-Z or a-z or _
\W none of the above
\d 0-9
\D none of 0-9
\s space or \t or \n (white space)
\S non space
\t tabulator
\n newline
\r carridge return
\b word boundary
\bkey matches key but not housekey
(?#.......) Comment
(?i) Case insensitive match. This can be inside a pattern variable.
(?:a|b|c) a or b or c, but without string in $n
(?=.....) Match ..... but do not store in $&
(?!.....) Anything but ..... and do not store in $&
Substitutions
One can replace found matches with a replacement with the s/pattern/replacement/;
statement.
The "s" is the command. Then there follow three delimiters with first a search pattern and
second a replacement between them. If there are "/" within the pattern or the replacement
then one chooses another delimiter than "/" for instance a "!".
chomp($var = <STDIN>);
Get Filenames
Get current directory at once
@dir = <*>;
Readdir()
Perl can also read a directory itself, without a globing shell. This is faster and more
controllable, but one has to use opendir() and closedir().
opendir(DIR,".") or die "Cannot open dir.\n";
while(readdir DIR){
rename $_,lc($_);
}
closedir(DIR);
chomp($date = qx!/usr/bin/date!); The chomp() (perl5) removes the trailing "\n". $date
gets the date.
chomp(@alllines = qx!/usr/bin/who!);
Array Functions
Get expressions for which a command
@found = grep(/[Jj]ohn/,@users);
returned true:
Applay a command to each element of an
@new = map(lc($_),@start);
array:
Put all array elements into a single string: $string = join(' ',@arr);
@data =
Split a string and make an array out of it:
split(/&/,$ENV{'QUERY_STRING'};
Sort an array: sort(@salery);
Reverse an array: reverse(@salery);
Get the keys of a hash(associative array): keys(%hash);
Get the values of a hash: values(%hash);
Get key and value of a hash iteratively: each(%hash);
Delete an array: @arr = ();
Delete an element of a hash: delete $hash{$key};
Check for a hash key: if(exists $hash{$key}){;}
Check wether a hash has elements: scalar %hash;
Cut of last element of an array and return
$last = pop(@IQ_list);
it:
Cut of first element of an array and return
$first = shift(@topguy);
it:
Append an array element at the end: push(@waiting,$name);
Prepend an array element to the front: unshift(@nowait,$name);
Remove first 2 chars an replace them with
splice(@arr,0,2,$var);
$var:
Get the number of elements of an array: scalar @arr;
Get the last index of an array: $lastindex = $#arr;
File Functions
Open a file for input: open(IN,"</path/file") || die "Cannot open file\n";
Open a file for output: open(OUT,">/path/file") || die "Cannot open file\n";
Open for appending: open(OUT,">>$file") || &myerr("Couldn't open $file");
Close a file: close OUT;
Set permissions: chmod 0755, $file;
Delete a file: unlink $file;
Rename a file: rename $file, $newname;
Make a hard link: link $existing_file, $link_name;
Make a symbolic link: symlink $existing_file, $link_name;
Make a directory: mkdir $dirname, 0755;
Delete a directory: rmdir $dirname;
Reduce a file's size: truncate $file, $size;
Change owner- and group-ID: chown $uid, $gid;
Find the real file of a symlink: $file = readlink $linkfile;
Get all the file infos: @stat = stat $file;
Conversions Functions
Number to character: chr $num;
Charachter to number: ord($char);
Hex to decimal: hex(0x4F);
Octal to decimal: oct(0700);
Get localtime from time: localtime(time);
Get greenwich meantime: gmtime(time);
Pack variables into string: $string = pack("C4",split(/\./,$IP));
Unpack the above string: @arr = unpack("C4",$string);
Call a Subroutine
&mysub;
Forking
Forking is very easy! Just fork. One puts the fork in a three way if(){} to separately the
parent, the child and the error.
if($pid = fork){
# Parent
command;
}elsif($pid == 0){
# Child
command;
# The child must end with an exit!!
exit;
}else{
# Error
die "Fork did not work\n";
}
if($pid = fork){
# Parent
close FROMPARENT;
close TOPARENT;
command;
}elsif($pid == 0){
# Child
close FROMCHILD;
close TOCHILD;
command;
exit;
}else{
# Error
command;
exit;
}
# Prepare infos
$port = 80;
$remote = 'remotehost.domain';
$iaddr = inet_aton($remote);
$paddr = sockaddr_in($port,$iaddr);
# Socket
socket(S,AF_INET,SOCK_STREAM,$proto) or die $!;
# Flush socket
select(S); $| = 1; select(STDOUT);
# Connect
connect(S,$paddr) or die $!;
# Print to socket
print S "something\n";
One can information for group, host, network, services, protocols in the above way with
the commands: getgrnam, getgrid, gethostbyname, gethostbyaddr, getnetbyname,
getnetbyaddr, getservbyname, getservbyport, getprotobyname, getprotobynumber.
If one wants to get all the entries of a particular category one can loop through them by:
setpwent;
while(@he = getpwent){
commands...
}
entpwent;
For example: Get a list of all users with their home directories:
setpwent;
while(@he = getpwent){
printf("%-20s%-30s\n",$he[0],$he[7]);
}
endpwent;
The same principle works for all the above data categories. But most of them need a
"stayopen" behind the set command.
Arithmetics
Addition: +
Subtraction: -
Multiplication: *
Division: /
Rise to the power of: **
Rise e to the pwoer of: exp()
Modulus: %
Square root: sqrt()
Absolut value: abs()
Tangens: atan2()
Sinus: sin()
Cosine: cos()
Random number: rand()
format filehandle =
@<<<<<<<<<<@###.#####@>>>>>>>>>>@||||||||||
$var1, $var3, $var4
.
Now use write to print into that filhandle according to the format:
write FILEHANDLE;
The @<<< does left adjustment, the @>>> right adjustment, @##.## is for numericals
and @||| centers.