Introduction to Perl Programming
Introduction to Perl Programming
( perl 5 )
( perl 5 )
Contents
Contents
Basics
Basics
Variables and Operators
Variables and Operators
Branching
Branching
Looping
Looping
File Test Operators
File Test Operators
Regular Expressions
Regular Expressions
Input and Output
Input and Output
Processing files mentioned on the Command
Processing files mentioned on the Command line
line
Get Filenames
Get Filenames
Pipe input and ouput
Pipe input and ouput from/to Unix Commands
from/to Unix Commands
Execute Unix Commands
Execute Unix Commands
The Perl built-in Functions
The Perl built-in Functions
Subroutines
Subroutines
Some of the special Variables
Some of the special Variables
Forking
Forking
Building Pipes for forked Children
Building Pipes for forked Children
Building a Socket Connecting to
Building a Socket Connecting to another Computer
another Computer
Get User and
Get User and Network Information
Network Information
Arithmetics
Arithmetics
Formatting Output with "format"
Formatting Output with "format"
Commandline Switches
Commandline Switches
Basics
Basics
Scripts
Scripts
Perl is a script language, which
Perl is a script language, which is compiled each time before running. That uis compiled each time before running. That unix knowsnix knows that it is a perl script there must be
that it is a perl script there must be the following header at the topline othe following header at the topline of every perl script:f every perl script:
#!/usr/bin/perl
#!/usr/bin/perlwhere the path to perl has to be correct and the line must not exeed 32where the path to perl has to be correct and the line must not exeed 32 charachters.
charachters.
Comments and Commands
Comments and Commands
After the header line:After the header line:#!/usr/bin/perl#!/usr/bin/perlthere are either empty lines with no effect or there are either empty lines with no effect or command lines or commentary lines. Everything from and
command lines or commentary lines. Everything from and behind a "behind a "##" up to the end of " up to the end of the line is comment and
the line is comment and has no effect on the program. Commands start with the has no effect on the program. Commands start with the first nonfirst non space charachter on a line and end with a "
space charachter on a line and end with a ";;". So one can continue a command over ". So one can continue a command over several lines and terminates it only with the semicolon.
several lines and terminates it only with the semicolon.
Direct commands and subroutines
Direct commands and subroutines
Normal commands are executedNormal commands are executed in the order written in the script. But subroutines can in the order written in the script. But subroutines can bebe placed anywhere and will only be evaluated when called from a normal command line. placed anywhere and will only be evaluated when called from a normal command line.
Perl knows it's a subroutine if it the code is preceded with a "sub" and enclosed in a block Perl knows it's a subroutine if it the code is preceded with a "sub" and enclosed in a block like:
like: sub name { command;}sub name { command;}
Other special lines
Other special lines
Perl can include other programming code with:
Perl can include other programming code with:require somethingrequire somethingor withor with useuse
something
something..
Quotations
Quotations
Single quote:Single quote:'''' or:or:q//q// Double quote:
Double quote:""""or:or:qq//qq// Quote for execution:
Quote for execution:```` or:or:qx//qx// Quote a list of words:
Quote a list of words: ('term1','term2','term3')('term1','term2','term3')or:or:qw/term1 term2 term3/qw/term1 term2 term3/ Quote a quoted string:
Quote a quoted string: qq/"$name" is $name/;qq/"$name" is $name/; Quote something wich contains "/":
Quote something wich contains "/":qq!/usr/bin/$file is readdy!;qq!/usr/bin/$file is readdy!;
Scalar and list context
Scalar and list context
That perl distinguishes between scalar and list context is the big feature, which makes it That perl distinguishes between scalar and list context is the big feature, which makes it unique and more useful then most other script languages.
unique and more useful then most other script languages.
A subroutine can return lists and not only scalars like in C. Or an
A subroutine can return lists and not only scalars like in C. Or an array gives the number array gives the number of elements in a scalar context
of elements in a scalar context and the elements itself in a list context.and the elements itself in a list context. The enormous value of that feature should be evident.
The enormous value of that feature should be evident.
V
V
ariables
ariables
and
and
Operators
Operators
General
General
There are scalar variables, one
There are scalar variables, one and two dimensional arrays and associative arrays. Insteadand two dimensional arrays and associative arrays. Instead of declaring a variable, one precedes it with a special character.
of declaring a variable, one precedes it with a special character.$variable$variableis a normalis a normal scalar variable.
scalar variable. @variable@variableis an array andis an array and %variable%variableis an associative array. The user of is an associative array. The user of perl does not have to distinguish between a number and a string in a variable. Perl
perl does not have to distinguish between a number and a string in a variable. Perl switches the t
switches the type if necessary.ype if necessary.
Scalars
Scalars
Fill in a scalar with:
Fill in a scalar with: $price = 300; $name = "JOHN";$price = 300; $name = "JOHN";Calculate with it like:Calculate with it like:$price *=$price *=
2; $price = $oldprice * 4; $count++; $worth--;
2; $price = $oldprice * 4; $count++; $worth--;Print out the value of a scalar Print out the value of a scalar with:with:
print $price,"\n";
print $price,"\n";
Arrays
Arrays
Fill in a value:Fill in a value:$arr[0] = "Fred"; $arr[1] = "John";$arr[0] = "Fred"; $arr[1] = "John";Print out this array:Print out this array: print join('print join('
',@arr),"\n";
',@arr),"\n"; If two dimensional:
If two dimensional: $arr[0][0] = 5; $arr[0][1] = 7;$arr[0][0] = 5; $arr[0][1] = 7;
Hashes (Associative Arrays)
Hashes (Associative Arrays)
Fill in a single element with:Fill in a single element with: $hash{'fred'} = "USA"; $hash{'john'} = $hash{'fred'} = "USA"; $hash{'john'} = "CANADA";"CANADA"; Fill in the entire hash:
Fill in the entire hash: %a = (
%a = (
'r1',
'r1', 'this 'this is is val val of of r1',r1',
'r2',
'r2', 'this 'this is is val val of of r2',r2',
'r3',
'r3', 'this 'this is is val val of of r3',r3',
); ); or with: or with: %a = ( %a = (
r1 => 'this is val of r1', r1 => 'this is val of r1', r2 => 'this is val of r2', r2 => 'this is val of r2', r3 => 'this is val of r3', r3 => 'this is val of r3', ); );
Assignments
Assignments
Put something into a variable with a "
Put something into a variable with a "==" or with some combined operator which " or with some combined operator which assignsassigns and does something at the same time:
and does something at the same time:
$var = "string";
$var = "string"; Puts the string into $var Puts the string into $var
$var = 5;
$var = 5; Puts a number into $var Puts a number into $var
$var .= "string";
$var .= "string";Appends string to $var Appends string to $var
$var += 5;
$var += 5;Adds number to $var Adds number to $var
$var *= 5;
$var *= 5;Multipliy with 5Multipliy with 5
$var ||= 5;
$var ||= 5; If $var is 0 make it 5If $var is 0 make it 5
$var x= 3;
$var x= 3; Make $var to three times $var as string: from a Make $var to three times $var as string: from a to aaato aaa Modify and assign with:
Modify and assign with:
($new = $old)
($new = $old) =~ s/pattern/replacement/;=~ s/pattern/replacement/;
Comparisons
Comparisons
Compare strings with:Compare strings with: eq neeq nelike in:like in: $name eq "mary"$name eq "mary".. Compare numbers with:
Compare numbers with:== != >= <= <=>== != >= <= <=> like in:like in:$price == 400$price == 400..
And/Or/Not
And/Or/Not
Acct on success or failure of an expression:
Acct on success or failure of an expression: $yes or die;$yes or die;means exit if $yes is not set.means exit if $yes is not set. For AND we have:
For AND we have:&&&& and "and "andand" and for OR we have:" and for OR we have: ||||or "or "oror". Not is "". Not is "!!" or "" or "notnot".". AND,OR and NOT are regularly used in if() statements:
AND,OR and NOT are regularly used in if() statements:
if($first && $second){....;}
if($first && $second){....;}
if($first || $second){....;}
if($first || $second){....;}
if($first && ! $second{....;}
if($first && ! $second{....;} means that $first must be non zero bmeans that $first must be non zero but $second must not beut $second must not be so.
so.
But many NOT's can be handled more reasonable with the unless() statement. Instead: But many NOT's can be handled more reasonable with the unless() statement. Instead:
print if ! $noway;
print if ! $noway; one uses:one uses:print unless $noway;print unless $noway;
Branching
if
if
if(condition){ if(condition){ command; command; }elsif(condition){ }elsif(condition){ command; command; }else{ }else{ command; command; } } command if condition; command if condition;unless (just the opposite of if)
unless (just the opposite of if)
unless(condition){ unless(condition){ command; command; }else{ }else{ command; command; } }command unless condition;
command unless condition;
Looping
Looping
while
while
while(condition){ while(condition){ command; command; } }# Go prematurely to the next iteration # Go prematurely to the next iteration
while(condition){ while(condition){ command; command; next if condition; next if condition; command; command; } }
# Prematureley abort the loop with last # Prematureley abort the loop with last
while(condition){ while(condition){ command; command; last if condition; last if condition; } }
# Prematurely continue the loop but do continue{} in any case # Prematurely continue the loop but do continue{} in any case
while(condition){ while(condition){ command; command; continue if condition; continue if condition; command; command; }continue{ }continue{
command;
command;
}
}
# Redo the loop without evaluating while(condtion) # Redo the loop without evaluating while(condtion)
while(condtion){ while(condtion){ command; command; redo if condition; redo if condition; } }
command while condition;
command while condition;
until (just the opposite of while)
until (just the opposite of while)
until(condition){ until(condition){ command; command; } } until(condition){ until(condition){ command; command; next if condition; next if condition; command; command; } } until(condition){ until(condition){ command; command; last if condition; last if condition; } } until(condition){ until(condition){ command; command; continue if condition; continue if condition; command; command; }continue{ }continue{ command; command; } }command until condtion;
command until condtion;
for (=foreach)
for (=foreach)
# Iterate over @data and have each value in $_ # Iterate over @data and have each value in $_
for(@data){ for(@data){ print $_,"\n"; print $_,"\n"; } }
# Get each value into $info iteratively # Get each value into $info iteratively
for $info (@data){
for $info (@data){
print $info,"\n";
print $info,"\n";
}
}
# Iterate over a range of numbers # Iterate over a range of numbers
for $num (1..100){ for $num (1..100){ next if $num % 2; next if $num % 2; print $num,"\n"; print $num,"\n";
}
}
# Eternal loop with (;;) # Eternal loop with (;;)
for (;;){ for (;;){ $num++; $num++; last if $num > 100; last if $num > 100; } }
map
map
# syntax # syntax map (command,list); map (command,list);map {comm1;comm2;comm3;} list;
map {comm1;comm2;comm3;} list;
# example # example
map (rename($_,lc($_),<*>);
map (rename($_,lc($_),<*>);
File Test Operators
File Test Operators
File test operators check for the status of
File test operators check for the status of a file: Some examples:a file: Some examples:
-f $file
-f $file It's a plain fileIt's a plain file
-d $file
-d $file It's a directoryIt's a directory
-r $file
-r $file Readable fileReadable file
-x $file
-x $file Executable fileExecutable file
-w $file
-w $file Writable fileWritable file
-o $file
-o $file We are owner We are owner
-l $file
-l $file File is a link File is a link
-e $file
-e $file File existsFile exists
-z $file
-z $file File has zero size, but existsFile has zero size, but exists
-s $file
-s $file File is greater than zeroFile is greater than zero
-t FILEHANDLE
-t FILEHANDLE This filehandle is connected to a ttyThis filehandle is connected to a tty
-T $file
-T $file Text fileText file
-B $file
-B $file Binary fileBinary file
-M $file
-M $file Returns the day number of last modification timeReturns the day number of last modification time
Regular Expressions
What it is
What it is
A regular expression is an abstract formulation of a string. Usually one has a search A regular expression is an abstract formulation of a string. Usually one has a search pattern and a match
pattern and a match which is the found string. There is also a replacement which is the found string. There is also a replacement for the match,for the match, if a substitution is made.
if a substitution is made.
Patterns
Patterns
A pattern stands for either one, any number, several, a particular number or none cases A pattern stands for either one, any number, several, a particular number or none cases of of a character
a character or a or a character-set given literallycharacter-set given literally, abstractly or , abstractly or octalyoctaly..
PATTERN
PATTERN MATCHMATCH .
. any character (dot)any character (dot)
.*
.* any number on any character (dot any number on any character (dot asterix)asterix)
a*
a* the maximum of consecutive a'sthe maximum of consecutive a's
a*?
a*? the minimum of consecutive a'sthe minimum of consecutive a's
.?
.? one or none of any charactersone or none of any characters
.+
.+ one or more of any character one or more of any character
.{3,7}
.{3,7} three up to seven of any characters, but as many as possiblethree up to seven of any characters, but as many as possible
.{3,7}?
.{3,7}? three up to seven, but the fewest number possiblethree up to seven, but the fewest number possible
.{3,}
.{3,} at least 3 of any character at least 3 of any character
.{3}
.{3} exactly 3 times any character exactly 3 times any character
[ab]
[ab] a or ba or b
[^ab]
[^ab] not a and also not bnot a and also not b
[a-z]
[a-z] any of a through zany of a through z
^a
^a
\Aa
\Aa a at beginning of stringa at beginning of string
a$
a$
a\Z
a\Z a at end of stringa at end of string
A|bb|CCC
A|bb|CCC A or bb or CCCA or bb or CCC
tele(f|ph)one
tele(f|ph)one telefone or telephonetelefone or telephone
\w
\w A-Z or a-z or _ A-Z or a-z or _
\W
\W none of the abovenone of the above
\d
\d 0-90-9
\D
\s
\s space or \t or \n (white space)space or \t or \n (white space)
\S
\S non spacenon space
\t
\t tabulator tabulator
\n
\n newlinenewline
\r
\r carridge returncarridge return
\b
\b word boundaryword boundary
\bkey
\bkey matches key but not housekeymatches key but not housekey
(?#...)
(?#...) CommentComment
(?i)
(?i) Case insensitive match. This can be inside a pCase insensitive match. This can be inside a pattern variable.attern variable.
(?:a|b|c)
(?:a|b|c) a or b or c, but without string in $na or b or c, but without string in $n
(?=...)
(?=...) Match ... but do not store in $&Match ... but do not store in $&
(?!...)
(?!...) Anything but ... and do not store in $&Anything but ... and do not store in $&
Substitutions
Substitutions
One can replace found matches with a replacement with the
One can replace found matches with a replacement with thes/pattern/replacement/;s/pattern/replacement/; statement.
statement.
The "s" is the command. Then
The "s" is the command. Then there follow three delimiters with first a search pattern andthere follow three delimiters with first a search pattern and second a replacement between them. If there are "/" within the pattern or the replacement second a replacement between them. If there are "/" within the pattern or the replacement then one chooses another delimiter than "/" for instance a "!".
then one chooses another delimiter than "/" for instance a "!". To change the content of a variable do:
To change the content of a variable do:$var =~ s/pattern/replacement/;$var =~ s/pattern/replacement/; T
To put the changed o put the changed value into another variable, without distorting the original variablevalue into another variable, without distorting the original variable do:
do:
($name = $line) =~ s/^(\w+).*$/$1/;
($name = $line) =~ s/^(\w+).*$/$1/;
COMMAND
COMMAND WHAT it DOESWHAT it DOES
s/A/B/;
s/A/B/; substitute the first a in a string with Bsubstitute the first a in a string with B
s/A/B/g;
s/A/B/g; substitute every a with a Bsubstitute every a with a B
s/A+/A/g;
s/A+/A/g; substitute any number of a with one Asubstitute any number of a with one A
s/^#//;
s/^#//; substitute a leading # with nothing. i.e remove itsubstitute a leading # with nothing. i.e remove it
s/^/#/;
s/A(\d+)/B$1/g;
s/A(\d+)/B$1/g; substitute a followed by a number with b substitute a followed by a number with b followed by thefollowed by the same number
same number
s/(\d+)/$1*3/e;
s/(\d+)/$1*3/e; substitute the found number with 3 times it's valuesubstitute the found number with 3 times it's value Use two "e" for to get
Use two "e" for to get an eval effect:an eval effect:
perl -e '$aa = 4; $bb
perl -e '$aa = 4; $bb = '$aa'; $bb =~ s/(\$\w+)/$1/ee; print $bb,"\n";'= '$aa'; $bb =~ s/(\$\w+)/$1/ee; print $bb,"\n";'
s/here goes date/$date/g;
s/here goes date/$date/g; substitute "here goes date" with the value of $datesubstitute "here goes date" with the value of $date
s/(Masumi) (Nakatomi)/$2
s/(Masumi) (Nakatomi)/$2
$1/g;
$1/g; switch the two termsswitch the two terms
s/\000//g;
s/\000//g; remove null charachtersremove null charachters
s/$/\033/;
s/$/\033/; append a ^M to make it readable for dosappend a ^M to make it readable for dos
Input and Output
Input and Output
Output a value from a variable
Output a value from a variable
print $var,"\n";print $var,"\n";
Output a formated string
Output a formated string
printf("%-20s%10d",$user,$wage);printf("%-20s%10d",$user,$wage);
Read in a value into
Read in a value into a variable and remove the newline
a variable and remove the newline
chomp() (perl5) removes a newline if onechomp() (perl5) removes a newline if one is there. The chop() (perl4) removes any lastis there. The chop() (perl4) removes any last character.
character.
chomp($var = <STDIN>);
chomp($var = <STDIN>);
Read in a file
Read in a file an process its linewise
an process its linewise
open(IN,"<filename") || die "Cannot open filename for input\n";
open(IN,"<filename") || die "Cannot open filename for input\n";
while(<IN>){
while(<IN>){
command;
}
}
close IN;
close IN;
Read a file into an array
Read a file into an array
open(AAA,"<infile") || die "Cannot open infile\n";
open(AAA,"<infile") || die "Cannot open infile\n";
@bigarray = <AAA>;
@bigarray = <AAA>;
close AAA;
close AAA;
Output into a file
Output into a file
open(OUT,">file") || die "Cannot oben file for output\n";
open(OUT,">file") || die "Cannot oben file for output\n";
while(condition){
while(condition){
print OUT $mystuff;
print OUT $mystuff;
}
}
close OUT;
close OUT;
Check, whether open file would yield something (eof)
Check, whether open file would yield something (eof)
open(IN,"<file") || die "Cannot open file\n";open(IN,"<file") || die "Cannot open file\n";
if(eof(IN)){
if(eof(IN)){
print "File is empty\n";
print "File is empty\n";
}else{ }else{ while(<IN>){ while(<IN>){ print; print; } } } } close IN; close IN;
Process Files mentioned on the
Process Files mentioned on the
Commandline
Commandline
The empty filehandle "<>" reads in ea
The empty filehandle "<>" reads in each file iterativelych file iteratively. The name of the current. The name of the current processed file is in
processed file is in $ARGV$ARGV. For example . For example print each line print each line of several files prepended of several files prepended withwith its filename: its filename: while(<>){ while(<>){ $file = $ARGV; $file = $ARGV; print $file,"\t",$_; print $file,"\t",$_;
open(IN,"<$file") or warn "Cannot open $file\n";
open(IN,"<$file") or warn "Cannot open $file\n";
....commands for this file....
....commands for this file....
close(IN); close(IN); } }
Get Filenames
Get Filenames
Get current directory at once
Get current directory at once
@dir = <*>;@dir = <*>;
Use current directory iteratively
Use current directory iteratively
while(<*>){ while(<*>){ ...commands... ...commands... } }Select files with <>
Select files with <>
@files = </longpath/*.c>;@files = </longpath/*.c>;
Select files with glob()
Select files with glob()
This is the official way of globbing: This is the official way of globbing:@files = glob("$mypatch/*$suffix");
@files = glob("$mypatch/*$suffix");
Readdir()
Readdir()
Perl can also read aPerl can also read a directory itself, without a globing shell. This is faster and moredirectory itself, without a globing shell. This is faster and more controllable, but one has to
controllable, but one has to use opendir() and closedir().use opendir() and closedir(). opendir(DIR,".") or die "Cannot open dir.\n";
opendir(DIR,".") or die "Cannot open dir.\n";
while(readdir DIR){ while(readdir DIR){ rename $_,lc($_); rename $_,lc($_); } } closedir(DIR); closedir(DIR);
Pipe Input and Output from/to Unix
Pipe Input and Output from/to Unix
Commands
Commands
Process Data from a Unix Pipe
Process Data from a Unix Pipe
open(IN,"unixcommand|") || die "Could not execute unixcommand\n";
open(IN,"unixcommand|") || die "Could not execute unixcommand\n";
while(<IN>){ while(<IN>){ command; command; } } close IN; close IN;
Output Data into a Unix Pipe
Output Data into a Unix Pipe
open(OUT,"|more") || die "Could not open the pipe to more\n";
open(OUT,"|more") || die "Could not open the pipe to more\n";
for $name (@names){
for $name (@names){
$length = length($name);
$length = length($name);
print OUT "The name $name consists of $lenght characters\n";
print OUT "The name $name consists of $lenght characters\n";
}
}
close OUT;
close OUT;
Execute Unix Commands
Execute Unix Commands
Execute a Unix Command and
Execute a Unix Command and forget about the Output
forget about the Output
system("someprog -auexe -fv $filename");system("someprog -auexe -fv $filename");
Execute a Unix Command an
Execute a Unix Command an store the Output into a
store the Output into a
Variable
Variable
If it's just one line or a string: If it's just one line or a string:
chomp($date = qx!/usr/bin/date!);
chomp($date = qx!/usr/bin/date!); The chomp() (perl5) removes the trailing "\n". $dThe chomp() (perl5) removes the trailing "\n". $dateate gets the date.
gets the date.
If it gives a series of lines one pu
If it gives a series of lines one put's the output into an array:t's the output into an array: chomp(@alllines = qx!/usr/bin/who!);
chomp(@alllines = qx!/usr/bin/who!);
Replace the whole perl program by a unix
Replace the whole perl program by a unix program
program
exec anotherprog;
The Perl built-in Functions
The Perl built-in Functions
String Functions
String Functions
Get all upper case with:Get all upper case with: $name = uc($name);$name = uc($name); Get only first letter uppercase:
Get only first letter uppercase: $name = ucfirst($name);$name = ucfirst($name); Get all lowercase:
Get all lowercase: $name = lc($name);$name = lc($name); Get only first letter lowercase:
Get only first letter lowercase: $name = lcfirst($name);$name = lcfirst($name); Get the length of a string:
Get the length of a string: $size = length($string);$size = length($string); Extract 5-th to 10-th characters from a string:
Extract 5-th to 10-th characters from a string: $part = substr($whole,4,5);$part = substr($whole,4,5); Remove line ending:
Remove line ending: chomp($var);chomp($var); Remove last character:
Remove last character: chop($var);chop($var); Crypt a string:
Crypt a string: $code = crypt($word,$salt);$code = crypt($word,$salt); Execute a string as perl code:
Execute a string as perl code: eval $var;eval $var; Show position of substring in string:
Show position of substring in string: $pos = index($string,$substring);$pos = index($string,$substring); Show position of last substring in string:
Show position of last substring in string: $pos = rindex($string,$substring);$pos = rindex($string,$substring); Quote all metacharachters:
Quote all metacharachters: $quote = quotemeta($string);$quote = quotemeta($string);
Array Functions
Array Functions
Get expressions for which a command Get expressions for which a command returned true:
returned true: @found = @found = grep(/[Jj]ohn/,@users)grep(/[Jj]ohn/,@users);; Applay a command to each element of an
Applay a command to each element of an array:
array: @new = map(lc($_),@start);@new = map(lc($_),@start); Put all array elements into a single string:
Put all array elements into a single string: $string = join(' ',@arr);$string = join(' ',@arr); Split a string and make an array out of it:
Split a string and make an array out of it: @data =@data =
split(/&/,$ENV{'QUERY_STRING'};
split(/&/,$ENV{'QUERY_STRING'}; Sort an array:
Sort an array: sort(@salery);sort(@salery); Reverse an array:
Reverse an array: reverse(@salery);reverse(@salery); Get the keys of a hash(associative array):
Get the keys of a hash(associative array): keys(%hash);keys(%hash); Get the values of a hash:
Get the values of a hash: values(%hash);values(%hash); Get key and value of
Delete an array:
Delete an array: @arr = ();@arr = (); Delete an element of a hash:
Delete an element of a hash: delete $hash{$key};delete $hash{$key}; Check for a hash key:
Check for a hash key: if(exists $hash{$key}){;}if(exists $hash{$key}){;} Check wether a hash has elements:
Check wether a hash has elements: scalar %hash;scalar %hash; Cut of last element of an array and
Cut of last element of an array and returnreturn it:
it: $last = pop(@IQ_list);$last = pop(@IQ_list); Cut of first element of an array and return
Cut of first element of an array and return it:
it: $first = shift(@topguy);$first = shift(@topguy); Append an array element at the end:
Append an array element at the end: push(@waiting,$name);push(@waiting,$name); Prepend an array element to the front:
Prepend an array element to the front: unshift(@nowait,$name);unshift(@nowait,$name); Remove first 2 chars an replace the
Remove first 2 chars an replace them withm with $var:
$var: splice(@arr,0,2,$var);splice(@arr,0,2,$var); Get the number of elements of an array:
Get the number of elements of an array: scalar @arr;scalar @arr; Get the last index of an
Get the last index of an array:array: $lastindex = $#arr;$lastindex = $#arr;
File Functions
File Functions
Open a file for input:Open a file for input: open(IN,"</path/file") || die "Cannot open file\n";open(IN,"</path/file") || die "Cannot open file\n"; Open a file for output:
Open a file for output: open(OUTopen(OUT,">/path/file") || die ,">/path/file") || die "Cannot open "Cannot open file\n";file\n"; Open for appending:
Open for appending: open(OUTopen(OUT,">>$file") || &myerr("Couldn't open ,">>$file") || &myerr("Couldn't open $file");$file"); Close a file:
Close a file: close OUT;close OUT; Set permissions:
Set permissions: chmod 0755, $file;chmod 0755, $file; Delete a file:
Delete a file: unlink $file;unlink $file; Rename a file:
Rename a file: rename $file, $newname;rename $file, $newname; Make a hard link:
Make a hard link: link $existing_file, $link_name;link $existing_file, $link_name; Make a symbolic link:
Make a symbolic link: symlink $existing_file, $link_name;symlink $existing_file, $link_name; Make a directory:
Make a directory: mkdir $dirname, 0755;mkdir $dirname, 0755; Delete a directory:
Delete a directory: rmdir $dirname;rmdir $dirname; Reduce a file's size:
Reduce a file's size: truncate $file, $size;truncate $file, $size; Change owner- and group-ID:
Change owner- and group-ID: chown $uid, $gid;chown $uid, $gid; Find the real file of a s
Find the real file of a symlink:ymlink: $file = readlink $linkfile;$file = readlink $linkfile; Get all the file infos:
Conversions Functions
Conversions Functions
Number to character:Number to character: chr $num;chr $num; Charachter to number:
Charachter to number: ord($char);ord($char); Hex to decimal:
Hex to decimal: hex(0x4F);hex(0x4F); Octal to decimal:
Octal to decimal: oct(0700);oct(0700); Get localtime from time:
Get localtime from time: localtime(time);localtime(time); Get greenwich meantime:
Get greenwich meantime: gmtime(time);gmtime(time); Pack variables into string:
Pack variables into string: $string = pack("C4",split(/\./,$IP));$string = pack("C4",split(/\./,$IP)); Unpack the above string:
Unpack the above string: @arr = unpack("C4",$string);@arr = unpack("C4",$string);
Subroutines (=functions in C++)
Subroutines (=functions in C++)
Define a Subroutine
Define a Subroutine
sub mysub { sub mysub { command; command; } } Example: Example: sub myerr { sub myerr {print "The following error occured:\n";
print "The following error occured:\n";
print $_[0],"\n"; print $_[0],"\n"; &cleanup; &cleanup; exit(1); exit(1); } }
Call a Subroutine
Call a Subroutine
&mysub; &mysub;Give Arg
Give Arguments to
uments to a Subroutine
a Subroutine
&mysub(@data);Receive Argu
Receive Arguments in
ments in the Subroutine
the Subroutine
As global variables: As global variables: sub mysub { sub mysub { @myarr = @_; @myarr = @_; } } sub mysub { sub mysub { ($dat1,$dat2,$dat3) = @_; ($dat1,$dat2,$dat3) = @_; } } As local variables: As local variables: sub mysub { sub mysub { local($dat1,$dat2,$dat3) = @_; local($dat1,$dat2,$dat3) = @_; } }Some of the Special Variables
Some of the Special Variables
S
SY
YN
NT
TA
AX
X
M
ME
EA
AN
NIIN
NG
G
$_
$_ String from current loop. e.g. for(@arr){ $field = $_ . " String from current loop. e.g. for(@arr){ $field = $_ . " ok"; }ok"; }
$.
$. Line number from current file processed with: while(<XX>){Line number from current file processed with: while(<XX>){
$0
$0 Program nameProgram name
$$
$$ Process id of current programProcess id of current program
$<
$< The real uid of current programThe real uid of current program
$>
$> Effective uid of current programEffective uid of current program
$|
$| For flushing output: select XXX; $| = 1;For flushing output: select XXX; $| = 1;
$&
$& The match of the last pattern searchThe match of the last pattern search
$1....
$1.... The ()-embraced matches of the last pattern searchThe ()-embraced matches of the last pattern search
$`
$` The string to the left of the last matchThe string to the left of the last match
$'
$' The string to the right of the last matchThe string to the right of the last match
Forking
Forking
Forking is very easy! Just fork. One puts the fork
Forking is very easy! Just fork. One puts the fork in a three way if(){} to separately thein a three way if(){} to separately the parent, the child and the error.
parent, the child and the error. if($pid = fork){ if($pid = fork){ # Parent # Parent command; command; }elsif($pid == 0){ }elsif($pid == 0){
# Child
# Child
command;
command;
# The child must end with an exit!!
# The child must end with an exit!!
exit; exit; }else{ }else{ # Error # Error
die "Fork did not work\n";
die "Fork did not work\n";
}
}
Building Pipes for forked Children
Building Pipes for forked Children
Building a Pipe
Building a Pipe
pipe(READHANDLE,WRITEHANDLE);
pipe(READHANDLE,WRITEHANDLE);
Flushing the Pipe
Flushing the Pipe
select(WRITEHANDLE); $| = 1; select(STDOUT);
select(WRITEHANDLE); $| = 1; select(STDOUT);
Setting up two Pipes between the Parent and a Child
Setting up two Pipes between the Parent and a Child
pipe(FROMCHILD,TOCHpipe(FROMCHILD,TOCHILD); ILD); select(TOCHILD); select(TOCHILD); $| $| = = 1; 1; select(STDOUT);select(STDOUT);
pipe(FROMPARENT,TOPARENT);select(TOPARENT);$| = 1; select(STDOUT); pipe(FROMPARENT,TOPARENT);select(TOPARENT);$| = 1; select(STDOUT); if($pid = fork){ if($pid = fork){ # Parent # Parent close FROMPARENT; close FROMPARENT; close TOPARENT; close TOPARENT; command; command; }elsif($pid == 0){ }elsif($pid == 0){ # Child # Child close FROMCHILD; close FROMCHILD; close TOCHILD; close TOCHILD; command; command; exit; exit; }else{ }else{ # Error # Error command; command; exit; exit; } }
Building a Socket Connection to another
Building a Socket Connection to another
Computer
# Somwhere at the beginning of the script # Somwhere at the beginning of the script
require 5.002; require 5.002; use Socket; use Socket; use sigtrap; use sigtrap; # Prepare infos # Prepare infos $port $port = = 80;80; $remote = 'remotehost.domain'; $remote = 'remotehost.domain'; $iaddr
$iaddr = = inet_aton($remote);inet_aton($remote);
$paddr
$paddr = = sockaddr_in($port,$iaddr);sockaddr_in($port,$iaddr);
# Socket # Socket socket(S,AF_INET,SOCK_STREAM,$proto) or die $!; socket(S,AF_INET,SOCK_STREAM,$proto) or die $!; # Flush socket # Flush socket select(S); $| = 1; select(STDOUT); select(S); $| = 1; select(STDOUT); # Connect # Connect connect(S,$paddr) or die $!; connect(S,$paddr) or die $!; # Print to socket # Print to socket print S "something\n"; print S "something\n";
# Read from socket # Read from socket
$gotit = <S>;
$gotit = <S>;
# Or read a single character only # Or read a single character only
read(S,$char,1);
read(S,$char,1);
# Close the socket # Close the socket
close(S);
close(S);
Get Unix User and Network Information
Get Unix User and Network Information
Get the password entry for a particular user with:
Get the password entry for a particular user with: @entry = getpwnam("$user");@entry = getpwnam("$user"); Or with bye user ID:
Or with bye user ID: @entry = getpwuid("$UID");@entry = getpwuid("$UID"); One can information for group, ho
One can information for group, host, network, services, protocols in the above wast, network, services, protocols in the above way withy with the commands:
the commands: getgrnam, getgrid, gethostbyname, ggetgrnam, getgrid, gethostbyname, gethostbyaddrethostbyaddr, getnetbyname,, getnetbyname, getnetbyaddr, getservbyname, getservbyport, getprotobyname, getprotobynumber getnetbyaddr, getservbyname, getservbyport, getprotobyname, getprotobynumber ..
If one wants to get all the entries of a particular category one can loop through them by: If one wants to get all the entries of a particular category one can loop through them by:
setpwent; setpwent; while(@he = getpwent){ while(@he = getpwent){ commands... commands... } } entpwent; entpwent;
For example: Get a list of all
For example: Get a list of all users with their home directories:users with their home directories: setpwent; setpwent; while(@he = getpwent){ while(@he = getpwent){ printf("%-20s%-30s\n",$he[0],$he[7]); printf("%-20s%-30s\n",$he[0],$he[7]); } } endpwent; endpwent;
The same principle works for all the
The same principle works for all the above data categories. But most of theabove data categories. But most of them need am need a ""stayopenstayopen" behind the set command." behind the set command.
Arithmetics
Arithmetics
Addition: Addition: ++ Subtraction: Subtraction: - -Multiplication: Multiplication:** Division: Division: //Rise to the power of: Rise to the power of:**** Rise e to the pwoer of:
Rise e to the pwoer of:exp()exp() Modulus:
Modulus: %% Square root:
Square root:sqrt()sqrt() Absolut value:
Absolut value:abs()abs() Tangens:
Tangens: atan2()atan2() Sinus:
Sinus: sin()sin() Cosine: Cosine:cos()cos() Random number:
Random number:rand()rand()
Formatting Output with "format"
Formatting Output with "format"
This should be simplification of the printf formatting. One formats once
This should be simplification of the printf formatting. One formats once only and then itonly and then it will be used for every write to a
will be used for every write to a specified file handle. Prepare a format somwhere in specified file handle. Prepare a format somwhere in thethe program: program: format filehandle = format filehandle = @<<<<<<<<<<@###.#####@>>>>>>>>>>@|||||||||| @<<<<<<<<<<@###.#####@>>>>>>>>>>@||||||||||
$var1, $var3, $var4
$var1, $var3, $var4
.
.
Now use write to print into that filhandle ac
Now use write to print into that filhandle according to the format:cording to the format: write FILEHANDLE;
The
The @<<<@<<<does left adjustment, thedoes left adjustment, the @>>>@>>>right adjustment,right adjustment, @##.##@##.##is for numericalsis for numericals and
and @|||@||| centers.centers.
Command line Switches
Command line Switches
Show the version number of perl:
Show the version number of perl: perl -v;perl -v; Check a new program without runing it:
Check a new program without runing it: perl -wc <file>;perl -wc <file>; Have an editing command on the command
Have an editing command on the command line:
line: perl -e 'command';perl -e 'command'; Automatically print while precessing lines:
Automatically print while precessing lines: perl -pe 'command' <file>;perl -pe 'command' <file>; Remove line endings and add them again:
Remove line endings and add them again: perl -lpe 'command' <file>;perl -lpe 'command' <file>; Edit a file in place:
Edit a file in place: perl -i -pe 'command' <file>;perl -i -pe 'command' <file>; Autosplit the lines while editing:
Autosplit the lines while editing: perl -a -e 'print if $F[3] =~ /ETH/;'perl -a -e 'print if $F[3] =~ /ETH/;'
<file>;
<file>; Have an input loop without printing: