Perl Programming Tutorial
Perl Programming Tutorial
Perl Programming Tutorial
Contents
[
Hide
]
UsingThePerlinterpreter
ImplicitExecution
ExplicitExecution
SimplePerlscript
CurrentpathtoPerlmodules
Variables
FindPerlInterpreter
UsingPerldefaultvariable$_
DefinedFunction
Scalarvariable
SingleQuotedStrings
Createandprintarray
CreateHash
NonDecimalIntegers
ScalarConstantVariable
StringAndNumericcomparisonOperators
Arrays
PushandPopArrays
DetermineTheLengthofanArray
MergeandAppendArrrays
SortArrays
DeleteElementfromanArray
Hash
AddElementtoaHash
PrintHash
MergingHashes
PerlRegularExpressions
RegularExpressionsandSpecialCharacters
Translation
MatchCharacters
Substitution
Substitutionwithevaluation
Classes
Quantifiers
Assertion
MultipleMatch
RegularExpressionExtention
Grouping
PerlSubroutines
StringOperators
Lists
DoubleQuotedStrings
CreateSimplePerlSubroutine
PassandReturnValues
Perloperators
PrecedenceofPerloperators
Perlforloop
Arrowoperator
IncrementandDecrementoperators
Loops
Perlwhileloop
Perluntilloop
Perlforeachloop
GettingUserInput
ReadFilePassedfromtheCommandline
OpenFileforReadandWrite
DetermineNumberofLinesinaFile
DetermineNumberofCharactersinaFile
SeekpositionwithinaFile
SimplePerlArithmetics
PerlOctal,Hexadecimal,AndDecimalConversions
CreatePerlPackage
Databasesconnections
ReadingCommandLineArguments
FileHandling
PerlMySQLdatabaseconnection
PerlPostgreSQLdatabaseconnection
ObjectOrientedPerl
Templateofget/setmethods
ThisPerlprogrammingtutorialisagreatscriptingguidetohelpyoufullyunderstandPerlscript.FindPerltutorialsand
programmingexamplestomasteryourknowledgeofPerlScripting.
http://linuxconfig.org/perlprogrammingtutorial
interpreterwhichinthiscaseisperl.
#!/usr/bin/perlprint"PerlProgramming\n"
MakePerlScriptExecutable:
chmod+xperl_script.pl
chmod+xperl_script.pl
perle'print"@INC"."\n"'
4. Variables
$ScalarVariable
%HashVariable
@Array
&Subroutines
#declareperlscalardobutnotdefinevalue
$perl_scalar
#wecanuseconditionaloperator'?:'totestperldefinedfuntion
$variable=defined($perl_scalar)?"Variable\$perl_scalarisDefined!"
:"Variable\$perl_scalarisNOTDefined!"
print$variable."\n"
#declareperlscalarwithvalue
$perl_scalar="perl"
$variable=defined($perl_scalar)?"Variable\$perl_scalarisDefined!"
:"Variable\$perl_scalarisNOTDefined!"
print$variable."\n"
#SingleQuotedscalarstrings
$scalar_string1='perl'
print"String1:".$scalar_string1."\n"
$scalar_string2='#!/usr/bin/perl'
print"String2:".$scalar_string2."\n"
$scalar_string3='Perl
Programming
Tutorial'
print"String3:".$scalar_string3."\n"
$scalar_string4='Perl\n'
print"String4:".$scalar_string4."\n"
$scalar_string5='\'\'\\'
print"String5:".$scalar_string5."\n"
$scalar_string6=''
print"String6:".$scalar_string6."\n"
$scalar_string7='I\'mreadingPerlProgrammingTutorial'
print"String7:".$scalar_string7."\n"
$scalar_string3="Perl
Programming
Tutorial"
print"String3:".$scalar_string3."\n"
$scalar_string4="Perl\n"
print"String4:".$scalar_string4."\n"
$scalar_string5="\'\'\\\""
print"String5:".$scalar_string5."\n"
$scalar_string6=""
print"String6:".$scalar_string6."\n"
#add"!"ASCIIcharacterinoctalform!=041
$scalar_string7="I\'mreadingPerlProgrammingTutorial\041"
print"String7:".$scalar_string7."\n"
#add"@"ASCIIcharacterinhexadecimalform@=40
$scalar_string8="Anyfeedbackaboutthis\uperl\uprogramming
\ututorialto:web\x40\lL\LINUXCONFIG.ORG\E"
print"String8:".$scalar_string8."\n"
#ScalarstringOperators
$scalar_string1="pe"."rl"
print"String1:".$scalar_string1."\n"
$scalar_string2="PerlProgrammingTutorial"x(1+1)
print"String2:".$scalar_string2."\n"
$scalar_string3="3"."\ttabs"x3
print"String3:".$scalar_string3."\n"
$scalar_string4="Perl\x20".'Programming'."Tutorial"
print"String4:".$scalar_string4."\n"
$scalar_string5=9x5
print"String5:".$scalar_string5."\n"
#perlbinaryinteger
$hash_binary_integer=0b10000
#perloctalinteger
$hash_octal_integer=020
#perlhexadecimalinteger
$hash_hexadecimal_integer1=0x10
$hash_hexadecimal_integer2=0x124c_78_aa
print$hash_octal_integer."\n"
print$hash_binary_integer."\n"
print$hash_hexadecimal_integer1."\n"
print$hash_hexadecimal_integer2."\n"
$ordinary_scalar=5
$ordinary_scalar=10
print$ordinary_scalar."\n"
#perlconstantdeclaration
*SCALAR_CONSTANT=5
$SCALAR_CONSTANT=10
String
Numeric
Equal
eq
==
NotEqual
ne
!=
Lessthan
lt
<
Greaterthan
gt
>
Lessthanorequal
le
<=
Greaterthanorequal
ge
>=
#!/usr/bin/perl
#Stringcomparison
if('Perl'eq'perl'){
print"TRUE\n"
}else{
print"FALSE\n"
}
#Numericcomparison
if('2.4'!='2.6'){
print"TRUE\n"
}else{
print"FALSE\n"
}
4.4. Lists
#!/usr/bin/perl
#ListsdefinitioninPerl
print("Perl","programming","Tutorial","\n")
4.5. Arrays
#CREATEANARRAY
@perl_array1=qw(PerlProgrammingTutorial)
@perl_array2=("Perl","Programing","Tutorial","\n")
@perl_array3=(1..3)
$perl_array4[0]="Perl"
$perl_array4[1]="Programming"
$perl_array4[2]="Tutorial"
$perl_array4[50]="\n"
#ADDELEMENTSTOANARRAY
$perl_array1[3]="\n"
#PRINTARRAY
print@perl_array1
print@perl_array2
print@perl_array3
print$perl_array1[3]
print@perl_array4
#Whatindexhasalastelementofanarray
print"Lastelementofperl_array4hasindex:".$#perl_array4."\n"
#CREATEANARRAY
@perl_array=(1..3)
#PUSHNEWELEMENTTOTHEANDOFANARRAY
push(@perl_array,"\n")
#PRINTARRAY
print@perl_array
#POPLASTELEMENTFROMANARRAY
$perl_scalar=pop(@perl_array)
print@perl_array
#PRINTNEWLINE
print$perl_scalar
#!/usr/bin/perl
#CREATEANARRAY
@perl_array=(1..3)
$number_of_elements=@perl_array
print"\@perl_arrayhas:".$number_of_elements."elements.\n"
print"\@perl_arrayhas:".scalar(@perl_array)."elements.\n"
#CREATEANARRAY
@perl_array1=(".\n","easy","very")
@perl_array2=("is","Programming","Perl")
@perl_array3=(@perl_array1,@perl_array2)
#REVERSINGELEMENTS
printreverse@perl_array3
#CREATEANARRAY
@perl_array=(3,4,1,2)
@sorted_array1=sort@perl_array
@sorted_array2=sort{$b<=>$a}@perl_array
print"@sorted_array1\n"
print"@sorted_array2\n"
#CREATEANARRAY
@perl_array=(1,2,3,4)
#CHECKIFTHEARRAYELEMENTEXISTS
if(exists($perl_array[2])){
delete$perl_array[2]
}else{
print"Arrayelementismising!\n"
}
print@perl_array,"\n"
4.6. Hash
#!/usr/bin/perl
#CREATEHASH
%perl_hash=(
browser=>iceweasel,
#youcanalsousecommainsteadofarrowoperator
os,linux,
)
#PRINTHASHELEMENT
print"$perl_hash{'browser'}\n"
#CREATEHASH
%perl_hash=(
browser=>iceweasel,
#youcanalsousecommainsteadofarrowoperator
os,linux,
)
#PRINTHASHELEMENT
print"$perl_hash{'browser'}\n"
#ADDELEMENTSTOAHASH
%perl_hash=(%perl_hash,programming,perl)
#PRINTALLELEMENTS
printjoin("",%perl_hash)."\n"
#CREATEHASH
%perl_hash=qw(
ssh22
http80
https443
telnet23
postgres5432
)
while(($hash_key,$hash_value)=each%perl_hash){
print"$hash_keyusesport$hash_value\n"
}
#CREATEHASH
%perl_hash1=qw(
Debiandeb
)
%perl_hash2=qw(
RedHatrpm
)
#MERGEHASHES
%perl_hash3=(%perl_hash1,%perl_hash2)
while(($hash_key,$hash_value)=each%perl_hash3){
print"$hash_key:$hash_value\n"
}
\d
Matchesdigitcharacter
\E
Endcasemodification
\e
\f
Formfeed
\L
Matcheslowercaseuntil\E
escape
found
\l
Nextcharacterlowercase
\n
Newline
\r
Return
\S
Matchanonwhitespace
\s
Matchawhitespace
\t
Matchtab
character
character
\U Matchuppercaseuntil\Efound
\u
Nextcharacteruppercase
\W Matchnonword
\w Matchword
\Q Quotepatternmetacharacteruntil\Efound
foreach(@ARGV){
#RegexMatchlowercaseanduppercasecharacter"p"(ignoresalphabeticcase)
if(m/p/i){$p1++}
#RegexMatchlowercasecharacter"p"only
if(m/p/){$p2++}
#RegexMatchtwocharacters"ex"andignorealphabeticcase
if(m/ex/i){$ex++}
}
print"p1=$p1\np2=$p2\nex=$ex\n"
5.3. Substitution
SampleFile:perl_regex.txt
#PerlRegularExpressions#
#CharacterSubstitute#
#!/usr/bin/perl
open(FILEHANDLE,$ARGV[0])||die"Problemsopeningfile"
@file=
foreach(@file){
#Substitute"#"with"$"andworkgloballyforeachinstancefound
#NOTE:allmetcharactersneedstobuescapedwith"\"likein
#thiscase"$"isescaped"\$"tobereadliterally
#Metacharactersare:\|{[()^$*+?.
s/\#/\$/g
#Substituteuppercase"E"withlowercase"e"
s/E/e/
#Substitutefirstmatchof""with"_"
s/\s/\_/
#Substitutefirstmatchof""with"\"
#Note:Isyourchoicewhichsubstituteformyouuses///ors|||
s|\s|\\|
print
}
#!/usr/bin/perl
my$text_eval=my$text_noeval="Hereissometexxxt.\n"
$text_noeval=~s/(xx+)/'(x^'.length($1).')'/
print"Textwithoutevaluation:".$text_noeval."\n"
$text_eval=~s/(xx+)/'(x^'.length($1).')'/e
print"Textwithevaluation:".$text_eval."\n"
linuxconfig.org:~$./subst_eval.pl
Textwithoutevaluation:Hereissomete'(x^'.length(xxx).')'t.
Textwithevaluation:Hereissomete(x^3)t.
5.4. Translation
#!/usr/bin/perl
$string="uSeREgularExpressionclaSSesTOtRanslatEFroMupPErcasetOlOwERcaSe
chArActErs"
#Useperltoconvertstringcharactersfromuppercasetolowercase
$string=~tr/AZ/az/
print"$string\n"
#Useperltoconvertstringcharactersfromlowercasetouppercase
$string=~tr/az/AZ/
print"$string\n"
5.5. Classes
A
regularexpressionsurroundedinsquarebracketsiscalleda
characterclass
whichmatchesanysinglecharacter
describedbytheregularexpression.
#!/usr/bin/perl
foreach(@ARGV){
#Substituteallcharacters"except^"uppercasecharactersandcharacter"e"with"#"
s/[^AZe]/\#/g
}
print"\n"
5.6. Quantifiers
#!/usr/bin/perl
@array1=@ARGV
@array2=@ARGV
print"\@array1="
foreach(@array1){
#Substituteatleast3"s"characters
s/s{3,}/SS/g
}
print"\n\@array2="
foreach(@array2){
#Substituteoneormore"s"characters
s/s+/S/g
}
print"\n"
5.7. Assertion
#!/usr/bin/perl
foreach(@ARGV){
#Substitutecharacter"a"andtheendofthestringwith"$"
s/a$/\$/g
#Substitutecharacter"a"andthebeginningofthestringwith"^"
s/^a/\^/g
print
}
print"\n"
$text="WewanttoimproveyourPerlRegularExpressionsskills."
print"NumberofSubstitutionsmade:".($text=~s/e/E/g)
print"\n$text\n"
MatchesIfwouldmatchnext
(?!)
MatchesIfwouldNOTmatchnext
(?<=) MatchesIfwouldmatchjustbefore
(?)
MatchesIfwouldNOTmatchjust
before
(?#)
=Comment
#!/usr/bin/perl
$_="WewantyoutoimproveyourPerlRegularExpressionsskills."
#Replacespacewith"#"ifitisfollowedby"to"
s/\s(?=to)/#/g
print"$_\n"
#Replacespacewith"_"ifitisNOTfollowedby"s"
s/\s(?!s)/_/g
print"$_\n"
5.10. Grouping
#!/usr/bin/perl
$a=$ARGV[0]
if($a=~/(.*)@(.*)\.(.*)/){
print"$1\n$2\n$3\n"
}
6. Perl Subroutines
6.1. Create Simple Perl Subroutine
#!/usr/bin/perl
#Letscreatesubroutinewhichwecanusetocheckforpresenceofnumberinthestring.
#Nameofthesubroutineisnumbers_in_string
subnumbers_in_string
{
if($mystring=~/[09]/){
print"Suppliedstringcontainsnumbers!\n"
}else{
print"SuppliedstringdoesNOTcontainnumbers!\n"
}
}
#declareglobalscopevariablewhichmeansthatthisvariablecanbeaccessedfrom
anywhereinthiscode.
$mystring="numberone"
#perlsubroutinecalls
numbers_in_string
$mystring="number1"
#perlsubroutinecalls
numbers_in_string
numbers_in_string($mystring)
subperl_addition{
#allvariablepassedtotheperlsubroutinesarestoredinspecial@_variable
($number1,$number2)=@_
#returntheresult
return$number1+$number2
}
#printresultbycallingperl_addition()subroutine
print"Number1+Number2=".perl_addition(4,2)."\n"
7. Perl operators
7.1. Precedence of Perl operators
Operators
Associativity
ParenthesesandListoperators
left
>
left
++
n/a
**
Right
!~\unary+unary
left
=~!~
left
*/%x
left
+.
left
<<>>
left
Namedunaryoperatorsandfiletest
n/a
operators
<><+>+ltgtlege
n/a
==!=<=>eqnecmp
n/a
&
left
|^
left
&&
left
||
left
.....
n/a
?:
right
=+=+*=
right
,=>
left
RightwardListoperators
n/a
not
right
and
left
orxor
left
#!/usr/bin/perl
print1+2*3+4."\n"
print((1+2)*(3+4))
print"\n"
#Printasafunctionoroperator
print((5+5)*5)print"\n"
print(5+5)*5print"\n"
#Useunary+operatortotellperl
#thatwearenotmakingprint()functioncall
#butratherusingparenthesesasaprecedence
print+(5+5)*5print"\n"
$perl_hash{browser}=iceweasel
$perl_hash_reference=\%perl_hash
print$perl_hash_reference>{browser}."\n"
$perl_scalar1=1
$perl_scalar2=2
$perl_scalar3='p'
$perl_scalar4='PERL'
print$perl_scalar1++.","
print$perl_scalar1.","
print++$perl_scalar3.","
print++$perl_scalar4."\n"
8. Loops
8.1. Perl for loop
#!/usr/bin/perl
#Definitionofperlforloop
for($for_loop=0$for_loop<=4$for_loop++){
print"forloopvalueis:".$for_loop."\n"
}
$while_loop=5
#Definitionofperlwhileloop
while($while_loop>=0){
print"whileloopvalueis:".$while_loop."\n"
$while_loop
}
#Definitionofperluntilloop
until($until_loop==0){
print"untilloopvalueis:".$until_loop."\n"
$until_loop
}
#Declarearray
@foreach_loop=("Tutorial\n","Scripting","Perl")
foreach$count(reverse@foreach_loop){
print$count
}
#gettinguserinput
$user_input=#alsopossibletousejust(<>)
print$user_input
#clearuserinputandremovenewlinecharacter
chomp($user_input)
print$user_input.""
[[Image:perl_user_input.gif]]
printjoin("",@ARGV)
print"\n".$ARGV[0].$ARGV[1].$ARGV[2].$ARGV[3].$ARGV[4].$ARGV[5]."\n"
#readallfilespassedbycommandlineasaarguments.
while(<>){
print
}
#CreatefilehandleforwritecalledWFILEHANDLEforfileperl.txt
#ifthefiledoesnotexistsitwillbecreated.
open(WFILEHANDLE,">perl.txt")ordie("Cannotopenperl.txt.\n")
#Insertdatatoperl.txt
printWFILEHANDLE"PerlProgrammingTutorial"
#Closefilehandle.
close(WFILEHANDLE)
#CreatefilehandleforreadcalledRFILEHANDLEforfileperl.txt
open(RFILEHANDLE,"
#readfileandprintto
while(){
print
}
print"\n"
open(FILEHANDLE,$ARGV[0])ordie("Couldnotopenagivenfile")
@lines=
print"NumberofLinesinthefile:".scalar(@lines)."\n"
#PerlcanPrintparticularlinefromthefile
print"Linenumber23:".$lines[22]."/n"
open(FILEHANDLE,$ARGV[0])ordie("Couldnotopenagivenfile")
my$input=0
while(defined($char=getcFILEHANDLE)){
$input++
}
print"Numberofcharacters:".$input."\n"
closeFILEHANDLE
#seekishelpfulperlfunction,especiallywithhugefiles,wheresequentialaccess
#maybetimeconsumingandmayrequirelotsofprocessingpower.Seekprovidesquick
randomaccess.
#0setthenewpositioninbytestoPOSITION
#1setthecurrentpositionplusPOSITION
#2setthenewpositionEOFplusPOSITION(oftennegative)
#useseekfunctiontosetposition20000bytes
open(FILEHANDLE,$ARGV[0])ordie("Couldnotopenagivenfile!!")
seekFILEHANDLE,20000,0
#useperltellfunctiontocheckfileposition.
printtellFILEHANDLE
print">seekFILEHANDLE,20000,0\n"
#Addanother36bytes
seekFILEHANDLE,36,1
printtellFILEHANDLE
print">seekFILEHANDLE,36,1\n"
#Returnpositiontobyte10
seekFILEHANDLE,10,0
printtellFILEHANDLE
print">seekFILEHANDLE,10,0\n"
#Setpositiontotheendofthefile(eof)
seekFILEHANDLE,0,2
printtellFILEHANDLE
print">seekFILEHANDLE,0,2\n"
closeFILEHANDLE
#perladdition
$addition=5+5.3
print"PerlAddition:\n5+5=".$addition."\n"
#perlsubtraction
$subtraction=10023
print"PerlSubtraction:\n10023=".$subtraction."\n"
#perlmultiplication
$multiplication=3*9
print"PerlMultiplication:\n3x9=".$multiplication."\n"
#perldivision
$division=45/5
print"PerlDivision:\n45:5=".$division."\n"
#perlmodulus
$modulus=10%3
print"PerlModulus:\n10%3=".$modulus."\n"
#perlexponential
$exponential=3**4
print"PerlExponential:\n3**4=".$exponential."\n"
#!/usr/bin/perl
print"\n"
#perlbintodec
#PERLCONVERSIONFROMBINARYTODECIMAL
$decimal_number=0b10010110
print"Binarynumber10010110is".$decimal_number."indecimal.\n"
#perldectobin
#PERLCONVERSIONFROMDECIMALTOBINARY
$decimal_number=23451
$binary_number=unpack("B32",pack("N",$decimal_number))
print"Decimalnumber".$decimal_number."is".$binary_number.
"inbinary.\n\n"
#perlocttodec
#PERLCONVERSIONFROMOCTALTODECIMAL
$octal_number=224
$decimal_number=oct($octal_number)
print"Octalnumber".$octal_number."is".$decimal_number."
indecimal.\n"
#perldectooct
#PERLCONVERSIONFROMDECIMALTOOCTAL
$decimal_number=8
$octal_number=sprintf("%o",$decimal_number)
print"Decimalnumber".$decimal_number."is".$octal_number."
inoctal.\n\n"
#perlhextodec
#PERLCONVERSIONFROMHEXADECIMALTODECIMAL
$hexadecimal_number="F1"
$decimal_number=hex($hexadecimal_number)
print"Hexadecimalnumber".$hexadecimal_number."is".
$decimal_number."indecimal.\n"
#perldectohex
#PERLCONVERSIONFROMDECIMALTOHEXADECIMAL
$decimal_number=333
$hexadecimal_number=sprintf("%x",$decimal_number)
print"Decimalnumber".$decimal_number."is".
$hexadecimal_number."inhexadecimal.\n\n"
#DECLAREPERLPACKAGE
packageperl_package
BEGIN{
#INITIALIZATIONCODE
#DEFINEPERLPACKAGE
subpackage_subroutine{
print"HellofromPerlPackage.\n"
}
#TOINDICATETHATPACKAGELOADSOK
return1
END{
#CLEANUPCODE
}
Withthefollowingscriptwecancallpackagesubroutine"package_subroutine":test_package.pl
#!/usr/bin/perl
useperl_package
perl_package::package_subroutine()
$mysql_host="perl_box"
$mysql_database="perl_connect"
$mysql_user="perl_programmer"
$mysql_password="perl"
$perl_mysql_connect=Mysql>connect($mysql_host,$mysql_database,
$mysql_user,$mysql_password)
if($perl_mysql_connect){
print"PerlhavecreatedconnectiontoMySQLdatabase!\n"
}else{
print"PerlcouldnotcreateconnectiontoMySQLdatabase!\n"
}
#loadperlpostgresqlmodule
useDBI
$postgresql_database=perl_connect
$postgresql_user=perl_programmer
$postgresql_password=perl
$postgresql_host=perl_box
#connecttoperltopostgresqldatabase
my$perl_postgresql=
DBI>connect("DBI:Pg:dbname=$postgresql_databasehost=$postgresql_host",
"$postgresql_user","$postgresql_password")
if($perl_postgresql){
print"PerlestablishedconnectiontoPostgreSQLdatabase\n"
}
linuxconfig:~/learn_perl/oo$$cattest.pl
#!/usr/bin/perl
usestrict
usewarnings
usePerson
my$p=Person>new()
$p>varName('Anna')
$p>varAge(30)
print$p>varName."is".$p>varAge."yearsold.\n"
Runningthisfunctionbehavesasexpected:
linuxconfig:~/learn_perl/oo$./test.pl
Annais30yearsold.
Theobviousimplementationofthisobjectwouldbeasfollows:
linuxconfig:~/learn_perl/oo$catPerson.pm
packagePerson
usestrict
usewarnings
subnew
{
my$class=shift
my$self={}bless($self,$class)
return$self
}
subvarName
{
my($self,$name)=@_
if(defined($name)){
$self>{NAME}=$name
}
return$self>{NAME}
}
subvarAge
{
my($self,$age)=@_
if(defined($age)){
$self>{AGE}=$age
}
return$self>{AGE}
}
1
ThemainthingtoobserveinthecodeaboveisthatthevarNameandvarAgeareidenticalinfunctionality.Intheexample
below,weimplementbothofthesemethodsusingasinglefunctiontemplate.
linuxconfig:~/learn_perl/oo$catPerson.pm
packagePerson
usestrict
usewarnings
subnew
{
my$class=shift
my$self={}bless($self,$class)
return$self
}
my@vars=qw(NameAge)
foreachmy$var(@vars){
nostrict'refs'#permitthesymbolicreferencestovarName,varAge
*{"var".$var}=
sub
{
my($self,$stuff)=@_
if(defined($stuff)){
$self>{uc($var)}=$stuff#changeNametoNAME
}
return$self>{uc($var)}
}
}
http://linuxconfig.org/perlprogrammingtutorial