You are on page 1of 7

RubyandPer

lCour
seFi
l
e-Tar
unJoshi
,JI
TBor
awan
DayOne
I
ntroduct
ion to Ruby
,Vari
ables i
n Ruby
,Rubymet
hods,Ar
it
hmet
ic and Rel
ati
onal
operat
ors,Logi
calandot
heroperat
ors.

I
ntr
oduct
iont
oRuby
,Whati
sRuby
?Feat
ures,
Rubygems,
Hel
ponr
uby
Decl
ari
ngandi
nit
ial
i
zingv
ari
abl
esi
nRuby
.
Whati
saMet
hod,
Wor
kingwi
thmet
hods,
Decl
ari
ngandCal
l
ingamet
hodset
c.
UseofAr
it
hmet
icandRel
ati
onal
oper
ator
sinRuby
.
UseofLogi
cal
oper
ator
sinRuby
.
Variabl
esar eusedtostorei
nformati
ontober ef
erencedandmanipulat
edinacomputer
program.Theyal sopr
ov i
deawayofl abel
ingdatawithadescri
pti
vename,soprogr
ams
can be under st
ood mor e cl
earl
y by anyone. v ar
iabl
es ar
e contai
nersthathold
i
nfor mat
ion.Theirsol
epurposeistolabelandstor
edat ai
nmemor y.Thi
sdatacanthen
beusedt hroughoutpr
ogram.

Nami ngvar
iablesi
sknownasoneoft hemostdiff
icul
ttasksi
ncomput erpr
ogr
ammi ng.
Wheny ouarenamingv ari
abl
es,thi
nkhar daboutthenames.makesur ethatt
hename
youassigny ourvari
ableisaccuratel
ydescript
iveandunder st
andabletoother
sor
your
selfwheny our
evisi
taprogram earl
i
er.

Assi
gni
ngValuet oVar
iabl
es-
Whenyouassignavar
iabl
e,y
ouusethe=symbol
.The
nameoft hevar
iabl
egoesonthel
eftandtheval
ueyouwantt
ostorei
nthevar
iabl
e
goesontheri
ght
.

Variabl
eScope: Av ari
abl
e'sscopedetermineswhereinapr ogram avariabl
eisav ail
able
foruse.Av ar
iable'
sscopeisdef i
nedbywher ethevari
ableisini
tial
izedorcr eated.In
Ruby ,v
ariabl
escopei sdefi
nedbyabl ock.Ablockisapieceofcodef ollowi
ngamet hod
i
nv ocati
on,usuallydeli
mitedbyei t
hercurlybraces{}ordo/ end.notal ldo/endpai rs
i
mpl yabl ock.
Innerscopecanaccessv ari
ablesini
ti
ali
zedinanout erscope,butnotv i
ce
versa.Getti
ngDat afrom aUser.

Method:pi eceofcodet hatneedst obeexecutedmanyt i


mesi naprogram.I nst
eadof
wri
ti
ng thatpi eceofcodeov erand over,ther
e'sa featur
ei n mostpr ogrammi ng
l
anguagescal ledapr ocedure,whi chall
owsy outoextractthecommoncodet oone
pl
ace.InRuby ,wecallitamet hod.Bef or
ewecanuseamet hod,wemustf irstdefi
neit
wi
thther eservedworddef .Afterthedefwegi veourmethodaname.Att heendofour
methoddef ini
ti
on,weuset her eservedwor
dendt odenot eit
scompl et
ion.Wecal l(or
i
nvoke)themet hodbytypi
ngi t
snameandpassi nginar
gument s.
Paramet
ersar
eusedwhenwehavedataoutsi
deofamethoddefi
niti
on'
sscope,
butyou
needaccesst
oitwit
hinthemet
hoddefini
ti
on.I
fthemethoddefi
niti
ondoesnotneed
accesst
oanyout
sidedat
a,wedonotneedtodef
ineanypar
ameters.

Methodsareamaj orpar tofpr


ogr amminginRuby.Knowi
ngwhatamet hodisandwhat
operati
onsi
tisperfor
mi ngiscrucialt
odevelopaRubyprogr
am.Knowingthediff
erence
betweenputsand r eturnwi l
lhel pyouav oi
d acommonpi tf
allt
hatweseemany
beginner
sstruggl
ewi t
h.Fi nal
ly,knowinghow andwhent ousemethodchai ni
ngwi l
l
hel
py oubet
terreadcodeandl etuswr it
egoodcode.

Oper
ati
ons:
Addi
ng,
Subt
ract
ing,
andMul
ti
ply
ingI
nteger
s

Basi
cmat hemati
caloper
ationsinRubyar
equitesi
mple.Toaddtwointeger
st ogether
j
ustusethe+operat
orasshownbel owini
rb.Makesur
et ot
ypetheseexamplesintoirb
andfeel
freetopl
aywithotherint
eger
saswell
.

Ther
ei salsoanoperatorcall
edthemodul ooperat
or.Thi
sisrepresent
edbyt he%
symbol.I
tcanberefer
redtoast heremainderoperat
oraswell
.Themodul ooperat
or
gi
vestheremai
nderofadivi
sionoper
ati
on.Logical
operat
orsar
ealsoused.

DayTwo
RubyContr
olStatements,forandforeachloopi
ng,whil
eandunt
ill
oopi
ng,obj
ect
ori
ent
edconcept
,objector
ient
edpr
ogrammingmethods.

Contr
olst
atement
sinRuby*Sy nt
axandusageof*i
fst
atement*el
sestat
ement*el
sif
st
atement*casest
atement*Exampl
eimplement
ati
onofeachoft
heabove

Useofforandeachl
oopi
nRuby
.whi
l
e&unt
ill
oopsi
nRuby*Usageofbr
eakwi
than
exampl
e

ObjectOr
ient
edConceptinRuby*Classesi
nRuby*Howtocreat
eobj
ects*Di
ffer
ent
way sofdefi
ningmethodsinRuby* Usi
ng?and=t odef
inemeani
ngfulmet
hods*
Examplei
mplementat
ionofeachoft
heabove

Methodsi
nRuby*Whatar
e*inst
ancemethods*classmethods*accessormet
hods*
Examplei
mpl
ement
ati
onofeachoft
heabove*Dif
ferencebet
weenthem

Thel
oopsi
nRubyar
e:

• whi
l
eloop

• f
orl
oop

• do.
.whi
l
eloop
• unt
ill
oop

The conditi
on which i
st o be t
ested,gi
ven atthe beginning oft he l
oop and all
stat
ement sareexecut
eduntilt
hegivenbool
eancondi
ti
onsat isfi
es.Whent hecondit
ion
becomesf alse,t
hecontrolwil
lbeoutf r
om thewhil
el oop.Itisal soknownasEnt r
y
Control
ledLoopbecauset hecondit
iontobetestedi
spr esentatt hebeginningofthe
l
oopbody .Sobasicall
y,whil
eloopisusedwhenthenumberofi t
erat i
onsisnotfi
xedin
aprogram.

Rubyuntilloopwil
lexecutesthestat
ementsorcodet i
l
lthegivenconditi
onevaluat
esto
true.Basicall
yit
’sjustoppositet othewhi l
el oop which execut
esuntilthegiven
condit
ionev al
uat
estof al
se.Anunt i
lst
atement’
sconditi
onali
ssepar at
edfr
om codeby
thereser
v edworddo,anewl i
ne,orasemicol
on.

Ruby is an object-
orient
ed programming language ( OOP)thatuses cl asses as
bluepr
int
sf orobj
ects.Object
sar et
hebasicbuilding-
blocksofRubycode(everythingin
Rubyisanobj ect)
,andhav etwomai nproper
ties:statesandbehavi
ours.Rubycl asses
arethebluepri
ntsthatestabl
ishwhatatt
ribut
es( alsoknownasst at
es)andbehav i
ours
(knowninRubyasmet hods)thatanobj
ectshouldhav e.

Rubydefinest heatt
ri
butesandbehav iorsofitsobjectsincl
asses.Youcanthinkof
cl
assesasbasi cout
li
nesofwhatanobj ectshouldbemadeofandwhati tshouldbe
abl
etodo.Todef i
neaclass,weusesy ntaxsimil
art
odef i
ningamethod.Werepl
acethe
defwit
hcl assanduset heCamel Casenami ngconventi
ontocreat
ethename.Wet hen
usethereservedwordendt ofi
nishthedefini
ti
on.

DayThr
ee
Over
view andi
nstal
lat
ionofPerl,Vari
abl
esinPer
l,Comment
sinPer
l,f
oreachl
oops,
whil
eanddowhileloops,Condi
ti
onalstat
ement
s.

Thi
stut
ori
altel
lsyouaboutPERLLanguageandt
hebenefi
tsofusi
ngPERL.I
tal
sot el
l
s
youaboutthei nst
all
ati
onstepsofPerlonUbuntuLinuxaswel lasonWi ndows
Oper
ati
ngSystem.

Var
iabl
esi
nPer
lwi
thexampl
es.

Comment
sinPer
l:Twot
ypesofcomment
s-1.Si
ngl
eLi
ne2.Mul
tiLi
ne

Useoff
orandf
oreachl
oopi
nPer
l,wi
thexampl
es.

Useofwhi
l
eanddowhi
l
eloopsi
nPer
l,wi
thexampl
es.

Useofi
fandi
fel
secondi
ti
onal
stat
ement
sinPer
l,wi
thexampl
es.
Useofi
f-
else-
ifandswi
tchcondi
ti
onal
stat
ement
sinPer
l.

A Perlvari
abl
enamest ar
tswitheit
her$,@ or% f oll
owedbyzer oormor elet
ter
s,
underscor
es,anddigi
ts(0to9).Per
ldoesnotall
owpunct uati
oncharacter
ssuchas@,
$,and%wi thi
nident
if
ier
s.Per
lisacasesensi
ti
veprogrammi nglanguage.

Simpl
ysay i
ngcomment si
nPerlstartwit
hahash#sy mbolandruntotheendofthe
l
ine.Li
nesst ar
ti
ng wit
h = ar
ei nt
erpret
ed asthestartofa secti
on ofembedded
documentat
ion(pod)
,andallsubsequentli
nesunt
ilt
henext=cutar ei
gnoredbythe
compil
er.

Per
lforloopstat
emental
l
owsy outoloopov erel
ement
sofal
ist
.Ineachi
terati
on,y
ou
canprocesseachel
ementofthelistsepar
ately
.Thi
siswhyt
heforloopstatementis
someti
mesr ef
err
edtoasfor
eachloop.

InPerl
,thef
orandfor
eachlooparei
nterchangeabl
e,t
her
efor
e,y
oucanuset
hef
oreach
keywordinwher
eyouusethefor
keyword.

Bothwhil
eanddowhi l
estatementter
minat
ethel
oopifthetestcondi
tioni
sfalse.
Unli
ket
hewhi l
estatementthatcheckst
hecondi
ti
onatthebegi
nningofeachi
ter
ation,
thedowhil
eloopstatement
checksthecondi
ti
onatt
heendofeachiter
ati
on.

Perlprovi
dest
hei
felsestat
ementt hatal
lowstoexecut
eacodebl
ockift
heexpr
essi
on
evaluat
estotr
ue,
otherwi
se,thecodeblockinsi
detheel
sebr
anchwi
ll
execut
e.

Aswi t
chstat
emental
l
owsav ar
iabl
etobetest
edforequal
it
yagai
nstali
stofvalues.
Eachv al
ueiscal
l
edacase,andthevar
iabl
ebeingswit
chedonischeckedforeach
swit
chcase.

• Theswi t
chst
atementt
akesasi
ngl
escal
arar
gumentofanyt
ype,speci
fi
edi
n
par
ent
heses.

• Thev
alueisf
oll
owedbyablock,whi
chmaycont
ainoneormor
ecasest
atement
f
oll
owedbyablockofPer
lst
atement(
s).

• Acasestat
ementtakesasinglescal
arar
gumentandselect
stheappr
opr
iat
e
t
ypeofmat
chi
ngbetweent
hecaseargumentandt
hecur
rentswi
tchval
ue.

• I
ft he match i
s successf
ul,t
he mandat
orybl
ock associ
ated wi
tht
he case
st
atementisexecut
ed.

• Aswitchstat
ementcanhaveanoptionalel
secase,whichmustappearatt
he
endoftheswit
ch.Thedef
aul
tcasecanbeusedforper
formingataskwhennoneoft
he
casesi
smatched.
• I
facaseblockexecut
esanuntar
getednext
,cont
rolisi
mmedi atel
ytransf
err
edto
thestat
ementaft
erthecasestat
ement(i
.e.
,usual
l
yanothercase)
,rathert
hanoutofthe
surr
oundingswi
tchblock.

• Notev
erycaseneedst ocontai
nanext
.Ifnonextappear
s,t
hef
lowofcont
rol
wil
l
notf
all
thr
oughsubsequentcases.

DayFour
Per
lDatastruct
ures,Arrayfunct
ions,Hash,Per
lfunct
ions,Bl
ocks,Accessmodi
fi
ers,
Ref
erenci
ngandDer ef
erenci
ng.

Di
ff
erentdat
ast
ruct
ureusedi
nPer
l,wi
thexampl
es.

Thi
stutori
alexpl
ainsvar
iousin-
bui
l
tarr
ayf unct
ions.Thesef
unct
ionsar
eused t
o
per
for
mv ari
ousact
ionsonarr
ayand/
orar
rayelements.

PERLHashisakeyval
uepairdat
astr
uctur
e.Hashisal
socall
edasassoci
ati
vear
ray
.
Hashisanun-
order
edcol
lecti
onofdata.Hashkey
sareuniquewhi
lev al
uescanbe
dupl
i
cate.

Perlhasi
tsownfunct
ionsplusall
owsustowrit
euser
-def
inedfunct
ions.Funct
ionscan
beusedtoperf
orm speci
fictask.I
tcantakesi
ngl
eormul t
ipl
earguments.Simil
arl
y,i
t
ret
urnssi
ngl
eormulti
plevaluesfr
om i
t.

PERLprovides5speci albl
ocks.TheseareBEGIN,END,UNITCHECK,CHECK&I NIT
bl
ocks.Theseblocksrunsatthestar
torattheendofPerlpr
ogram.Wecanusethese
bl
ocks;Toincl
udef i
l
esatt hestar
tofprogr
am.Forini
ti
ali
zat
ionpur
poseortodest
roy
obj
ectsandtheendofPer lPr
ogram.

AccessModifiersi
nPERL1.pr i
vatevar
iable-myscopei
sintheblocki
nsidewhereiti
s
declar
ed2.lexical
l
yscopedv ari
ables-localt
hatmeanstheygetthetemporar
yv al
ue
i
nsidethebl
ock3.gl obalv
ari
ables-ourcanbeaccessedwithoutgi
vi
ngpackagename
whil
eaccessingiti
nanotherpackage

Refer
enci
ng:Cr eatear eference by adding \(backward slash)Demo ofv ari
ous
examplesAdd,r emove,accesselement sofarrayreference/hashr ef
erenceinthe
scri
ptwit
hexampl es.Deref
erenci
ng:Gett heactualenti
tybeingrefer
redbyr ef
erence.
Demoofv ar
iousexamples

Speci
alvar
iableshaveapredefi
nedandspeci
almeani
nginPerl
.2.Thesevar
iablesare
denotedbyusualvari
abl
eindicat
orsuchas$,@,%alongwit
hpunctuati
oncharacter
s.
ForExample:$_,$!
,$@
Perlisal ooselytypedlanguageandt hereisnoneedt ospecifyat
ypeforyourdat
awhile
usingi nyourpr ogram.ThePer l
inter
preterwillchoosethety
pebasedont hecontextof
thedat aitsel
f.Perlhasthreebasicdat atypes:scalar
s,ar
raysofscal
ars,
andhashesof
scalars,alsoknownasassoci at
ivearrays.

Arr
ayscangr ow andshri
nk.ThePerlarr
ayf uncti
onsall
ow youtoi nsertordelet
e
el
ementsofthearrayf
rom thefr
ont
,middle,orendofthelist
,tosor
tar r
ays,per
form
cal
cul
ati
onsonelements,
tosear
chforpat
terns,andmore.

Per lar
rayasast ackwithpush(
)andpop( )f
unct
ions.Bothfunct
ionstr
eatanarr
ayasa
stack.Ast ackwor ksbasedonlastinfir
stout(LI
FO)philosophy.I
tworksexactl
ythe
sameasast ackofbooks.Thepush()functi
onappendsoneormor eelementstothe
endoft hear r
ay,whil
ethepop()funct
ionremovesthelastelementfr
om theendofthe
array.

Arr
aysareor
dered,andyouaccessanelementofanar
rayusingit
snumer i
cali
ndex.
Hashesar
eun-or
deredandyouaccessav
alueusi
ngakeywhichisastr
ing.

Eachhashkeyisassoci
atedwit
hasingl
ev al
ueandthekeysareal
luni
quei
nsi
dea
si
ngl
ehashstr
uctur
e.Thatmeansnor
epet
it
ivekeysar
eall
owed.

DayFi
ve
Fi
l
ehandli
ngi nPerl
,Except
ionander
rorhandli
ng,i
ncl
udi
ngf
il
esormodul
es,Per
l
modul
eli
brar
y,downl
oadi
ngCPANmodule,
PerlandHTML.

I
ntroduct
iontoexcept
ionhandl
inginPer
l.Whenaner
roroccur
s,except
ionander
ror
handli
nghelpst
orecovert
heprogr
am.

Fi
leHandl
ing:1.OpenaFi
l
e2.OpenaFil
einReadMode3.OpenaFi
l
einWr
it
eMode4.
OpenaFil
einAppendMode5.Cl
osetheFil
eHandl
e

I
ncl
udi
ngFi
l
esormodul
esi
nPer
lpr
ogr
am wi
thexampl
es.

ASampl
ePer
lpr
ogr
am whi
chwi
l
lgi
vet
heout
putofv
ari
ousweat
herf
orecastr
epor
tsof
ar
egi
on.

Compr
ehensi
vePer
lAr
chi
veNet
wor
k(CPAN)i
sthel
i
brar
yofmodul
es.

Downl
oadi
ngCPANmodul
eonWi
ndowspl
atf
orm andLi
nuxpl
atf
orm.

TocreateHTMLpages,Perlprovi
desCGImodul ewhi
chcreatesCGIscri
ptwit
hrequi
re
HTMLt ags.2.Ther
earedif
ferentmethodswhichCGImodul esprov
idetoaddheader
,
addi
ngfiel
dstothepage,
retr
ievi
ngthevaluesoft
heparameterspost
edontothefor
m.

1.Get
ti
ngLasti
ndexofar
ray2.Get
ti
ngl
engt
hofanar
ray
,Togett
hel
engt
h,add1t
o
l
asti
ndexofanar r
ay,
Otherwayisusescal
arfunct
iononarr
ayorassi
gnar
rayascal
ar
v
ari
able.3.Accessi
ngelementofanar
ray4.Loopi
ngoveranarr
ay

Err
orHandlinginPerli
stheprocessoft
aki
ngappr
opr
iat
eact
ionagai
nstapr
ogr
am t
hat
causesdiff
icul
tyinexecutionbecauseofsomeerrorint
hecodeort hecompi
ler
.
Processesarepronetoerr
ors.

Per
lpr
ovi
dest
wobui
l
tinf
unct
ionst
ogener
atef
atal
except
ionsandwar
nings,
thatar
e:

1. di
e()

2. war
n()

Ot
hermet
hodst
hatcanbeusedf
orhandl
i
ngEr
ror
s

• i
fst
atement

• unl
essf
unct
ion

• Er
ror‘
:
try
’modul
e

APer
lmodul
eisareusabl
epackagedef
inedinali
brar
yfi
l
ewhosenamei
sthesameas
t
henameoft
hepackage(wit
ha.pm ontheend)
.

APer lmoduleisar eusabl


ecollect
ionofrel
atedvari
ablesandsubrouti
nest hatperf
orm
a setofpr ogramming tasks.There areal otofPer lmodul es avail
able on t he
Compr ehensivePerlArchi
veNet work(CPAN).Youcanf indvari
ousmodul esi nawi de
rangeofcategor i
essuchasnetwor k,
XMLpr ocessi
ng,CGI,dat
abasesinterf
acing,et
c.

Tof i
ndaspeci f
icmodulef oryourproj
ect,checkitouttheCPANSear chsecti
on.The
Compr ehensiv
ePer lArchi
veNet work(CPAN)i sar eposi
tor
yofov er250,000softwar
e
modulesandaccompany i
ngdocument at
ionf or39,000di
str
ibut
ions,writ
teninthePerl
progr
ammi nglanguagebyov er12,
000cont r
ibutor
s.MostsoftwareonCPANi sfreeand
opensour cesoftware.

I
ti spossibl
et osetuptheHTTPser versothatwhenev
erafilei
nacer t
aindir
ectoryis
requestedthatfi
leisnotsentback;inst
eaditi
sexecut
edasapr ogram,andwhat ever
thatprogram out
putsissentbackforyourbr
owsertodi
spl
ay.Thi
sfuncti
oniscall
edt he
CommonGat ewayInt
erf
aceorCGIandt hepr
ogramsarecal
ledCGIscri
pts.TheseCGI
programscanbeaPERLScr i
pt.

You might also like