You are on page 1of 43

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

1. Using The Perl interpreter


1.1. Find Perl Interpreter
whichperl

1.2. Implicit Execution


NOTE:
Everyscriptstartswith
shebang:"#!"
whichisnotreadasacomment.Firstlineisalsoaplacewhereyouputyour

interpreterwhichinthiscaseisperl.

#!/usr/bin/perlprint"PerlProgramming\n"

MakePerlScriptExecutable:

chmod+xperl_script.pl

1.3. Explicit Execution


print"PerlProgramming\n"
MakePerlScriptExecutable:

chmod+xperl_script.pl

2. Simple Perl script


#!/usr/bin/perl#print"PerlProgrammingTutorial\n"

3. Current path to Perl modules


Listallavailablecurrentpathstoperlmodules:

perle'print"@INC"."\n"'

4. Variables
$ScalarVariable

%HashVariable
@Array
&Subroutines

4.1. Using Perl default variable $_


#!/usr/bin/perl
$_="PerlProgrammingdefaultvariable.\n"
print

4.2. Defined Function


#!/usr/bin/perl

#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"

4.3. Scalar variable


#!/usr/bin/perl
#Scalarsholdjustsingledatatype:string,numberorperlreference
#ScalarsdefinitioninPerl
$scalar_number=5
$scalar_string1="InPERLScalarsarealwaysreferencedwith\x24infrontofeach
variablename."
$scalar_string2="5items"
#Undescorecanbeuseforbignumbers
$scalar_milion=1_000_000
#Printscalarvalues
print$scalar_number."\n"
print$scalar_string1."\n"
print$scalar_string2."\n"
print$scalar_milion."\n"
#perlscalaraddition
print$scalar_number+$scalar_milion."\n"

4.3.1. Single-Quoted Strings


#!/usr/bin/perl

#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"

4.3.2. Double-Quoted Strings


#!/usr/bin/perl
#DoubleQuotedscalarstrings
$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"
#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"

4.3.3. String Operators


#!/usr/bin/perl

#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"

4.3.4. Non-Decimal Integers


#!/usr/bin/perl

#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"

4.3.5. Scalar Constant Variable


#!/usr/bin/perl

$ordinary_scalar=5
$ordinary_scalar=10

print$ordinary_scalar."\n"

#perlconstantdeclaration
*SCALAR_CONSTANT=5
$SCALAR_CONSTANT=10

4.3.6. String And Numeric comparison Operators


Comparison

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

4.5.1. Create and print array


#!/usr/bin/perl

#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"

4.5.2. Push and Pop Arrays


#!/usr/bin/perl

#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

4.5.3. Determine The Length of an Array

#!/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"

4.5.4. Merge and Append Arrrays


#!/usr/bin/perl

#CREATEANARRAY

@perl_array1=(".\n","easy","very")
@perl_array2=("is","Programming","Perl")
@perl_array3=(@perl_array1,@perl_array2)
#REVERSINGELEMENTS
printreverse@perl_array3

4.5.5. Sort Arrays


#!/usr/bin/perl

#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"

4.5.6. Delete Element from an Array


#!/usr/bin/perl

#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

4.6.1. Create Hash

#!/usr/bin/perl

#CREATEHASH
%perl_hash=(
browser=>iceweasel,
#youcanalsousecommainsteadofarrowoperator
os,linux,
)
#PRINTHASHELEMENT
print"$perl_hash{'browser'}\n"

4.6.2. Add Element to a Hash


#!/usr/bin/perl

#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"

4.6.3. Print Hash


#!/usr/bin/perl

#CREATEHASH
%perl_hash=qw(
ssh22
http80
https443
telnet23
postgres5432
)

while(($hash_key,$hash_value)=each%perl_hash){
print"$hash_keyusesport$hash_value\n"
}

4.6.4. Merging Hashes


#!/usr/bin/perl


#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"
}

5. Perl Regular Expressions


5.1. Regular Expressions and Special Characters
\D Matchesnondigitcharacter

\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

5.2. Match Characters


#!/usr/bin/perl

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
}

5.3.1. Substitution with evaluation


Incaseastringistobesubstitutedwiththeoutputofafunctioncallratherthanstatictextwecanusetheevaluation
modifier(/e)whichevaluatestherighthandsideas
code,
ratherthanastring.

#!/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

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

}
print"\n\@array2="
foreach(@array2){
#Substituteoneormore"s"characters
s/s+/S/g

print

}
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"

5.8. Multiple Match


#!/usr/bin/perl
#/gmatchglobally
$text="WewanttoimproveyourPerlRegularExpressionsskills."
print"NumberofSubstitutionsmade:".($text=~s/e/E/)
print"\n$text\n"

$text="WewanttoimproveyourPerlRegularExpressionsskills."
print"NumberofSubstitutionsmade:".($text=~s/e/E/g)
print"\n$text\n"

5.9. Regular Expression Extention


(?=)

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)

6.2. Pass and Return Values


#!/usr/bin/perl

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"

7.2. Arrow operator


#!/usr/bin/perl

$perl_hash{browser}=iceweasel
$perl_hash_reference=\%perl_hash
print$perl_hash_reference>{browser}."\n"

7.3. Increment and Decrement operators


#!/usr/bin/perl

$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"
}

8.2. Perl while loop


#!/usr/bin/perl
#

$while_loop=5


#Definitionofperlwhileloop
while($while_loop>=0){
print"whileloopvalueis:".$while_loop."\n"
$while_loop
}

8.3. Perl until loop


#!/usr/bin/perl
#
$until_loop=5

#Definitionofperluntilloop
until($until_loop==0){
print"untilloopvalueis:".$until_loop."\n"
$until_loop
}

8.4. Perl foreach loop


#!/usr/bin/perl


#Declarearray

@foreach_loop=("Tutorial\n","Scripting","Perl")
foreach$count(reverse@foreach_loop){
print$count
}

9. Getting User Input


#!/usr/bin/perl

#gettinguserinput
$user_input=#alsopossibletousejust(<>)
print$user_input
#clearuserinputandremovenewlinecharacter
chomp($user_input)
print$user_input.""

[[Image:perl_user_input.gif]]

9.1. Reading Command Line Arguments


#!/usr/bin/perl
#readingcommandlineargumentswithperl
#@ARGVisPerlbuildinarraywhich
#containsallargumentspassedduringcommandlineexecution

printjoin("",@ARGV)

print"\n".$ARGV[0].$ARGV[1].$ARGV[2].$ARGV[3].$ARGV[4].$ARGV[5]."\n"

10. File Handling


10.1. Read File Passed from the Command line
#!/usr/bin/perl

#readallfilespassedbycommandlineasaarguments.
while(<>){
print
}

10.2. Open File for Read and Write


#!/usr/bin/perl

#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"

10.3. Determine Number of Lines in a File


#!/usr/bin/perl

open(FILEHANDLE,$ARGV[0])ordie("Couldnotopenagivenfile")

@lines=
print"NumberofLinesinthefile:".scalar(@lines)."\n"
#PerlcanPrintparticularlinefromthefile
print"Linenumber23:".$lines[22]."/n"

10.4. Determine Number of Characters in a File


#!/usr/bin/perl

open(FILEHANDLE,$ARGV[0])ordie("Couldnotopenagivenfile")
my$input=0
while(defined($char=getcFILEHANDLE)){
$input++
}
print"Numberofcharacters:".$input."\n"
closeFILEHANDLE

10.5. Seek position within a File


#!/usr/bin/perl

#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

11. Simple Perl Arithmetics


#!/usr/bin/perl

#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"

12. Perl Octal, Hexadecimal,


And Decimal Conversions

#!/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"

13. Create Perl Package


Hereisanexampleofsimpleperlpackage:perl_package.pm

#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()

14. Databases connections


14.1. Perl MySQL database connection
#!/usr/bin/perl
#
useMysql


$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"
}

14.2. Perl PostgreSQL database connection


#!/usr/bin/perl

#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"
}

15. Object Oriented Perl


TherearemanymaterialsfocussedonobjectorientedPerlfromtheintroductoryPerlBoottothemorecomprehensive
PerlToot.Inthissectionaretopicsorviewpointswhichcouldn'tbefoundelsewhere.

15.1. Template of get/set methods


Belowisanexampleofascriptusinganobjectwithtwopiecesofdatawithamethodtoset/geteachone:varNameand
varAge.

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

You might also like