Sunteți pe pagina 1din 364

UNIT I INTRODUCTION Introduction to Open sources Need of Open Sources Advantages of Open Sources Application of Open Sources.

s. Open source operating systems: LINUX: Introduction General Overvie !ernel "ode and user mode #rocess Advanced $oncepts Sc%eduling #ersonalities $loning Signals &evelopment it% Linu'. . 1. Introduction 1.1. Introduction to Open Sources "ost soft are t%at you (uy or do nload only comes in t%e compiled ready)to)run version. $ompiled means t%at t%e actual program code t%at t%e developer created* +no n as t%e source code* %as run t%roug% a special program called a compiler t%at translates t%e source code into a form t%at t%e computer can understand. It is e'tremely difficult to modify t%e compiled version of most applications and nearly impossi(le to see e'actly %o t%e developer created different parts of t%e program. "ost commercial soft are manufacturers see t%is as an advantage t%at +eeps ot%er companies from copying t%eir code and using it in a competing product. It also gives t%em control over t%e ,uality and features found in a particular product. Open source soft are is at t%e opposite end of t%e spectrum. -%e source code is included it% t%e compiled version and modification or customi.ation is actually encouraged. What is the difference between Free Software & Open Source Software /ree Soft are* or /ree are* is usually freely distri(uted soft are t%at* depending on t%e aut%or0s re,uest* you can redistri(ute it%out modifying it. "ost Open Source soft are is covered (y t%e G#L 1General #u(lic License2 as t%e original or+. Definition of Open Source
1 Sree Sakthi Engineering College

%ic% means

you can modify it* and redistri(ute your modifications to it so long as you don0t try to pass it off

A defined set of re,uirements for open source soft are from t%e Open Source Initiative 1OSI2. -%e Open Source &efinition 1OS&2 specifies not only access to t%e source code* (ut also integrity of t%e code* its free redistri(ution* a tec%nology)neutral provision* as anti)discrimination rules. Open source refers to any program pu(lic colla(oration and made freely availa(le. Open source soft are refers to applications developed in alter t%e 3source3 code itself. !rincipa" of Open Source Software Open source doesn0t 4ust mean access to t%e source code. -%e distri(ution terms of open) source soft are must fulfill it% t%e follo ing criteria: 1. Free Redistribution -%e license s%all not restrict any party from selling or giving a ay t%e soft are as a component of an aggregate soft are distri(ution containing programs from several different sources. -%e license s%all not re,uire a royalty or ot%er fee for suc% sale. #. Source Code -%e program must include source code* and must allo distri(ution in source code as ell as compiled form. 5%ere some form of a product is not distri(uted cost prefera(ly* do nloading via t%e Internet preferred form in are not allo ed. $. Deri%ed Wor&s -%e license must allo modifications and derived or+s* and must allo t%em to (e distri(uted under t%e same terms as t%e license of t%e original soft are. '. Inte(rit) of the *uthor+s Source Code
2 Sree Sakthi Engineering College

ell as specific

%ose source code is made availa(le for use or

modification as users or ot%er developers see fit. Open source soft are is usually developed as a %ic% t%e user can access and

it% source code* t%ere must (e

a ell)pu(lici.ed means of o(taining t%e source code for no more t%an a reasona(le reproduction it%out c%arge. -%e source code must (e t%e %ic% a programmer ould modify t%e program. &eli(erately o(fuscated

source code is not allo ed. Intermediate forms suc% as t%e output of a preprocessor or translator

-%e license may restrict source)code from (eing distri(uted in modified form only if t%e license allo s t%e distri(ution of 3patc% files3 it% t%e source code for t%e purpose of modifying t%e or+s to carry a different name or program at (uild time. -%e license must e'plicitly permit distri(ution of soft are (uilt from modified source code. -%e license may re,uire derived version num(er from t%e original soft are. ,. No Discri-ination a(ainst !ersons or .roups -%e license must not discriminate against any person or group of persons. /. No Discri-ination a(ainst Fie"ds of 0ndea%or -%e license must not restrict anyone from ma+ing use of t%e program in a specific field of endeavor. /or e'ample* it may not restrict t%e program from (eing used in a (usiness* or from (eing used for genetic researc%. 1. Distribution of 2icense -%e rig%ts attac%ed to t%e program must apply to all to 3. 2icense 4ust Not 5e Specific to a !roduct -%e rig%ts attac%ed to t%e program must not depend on t%e program0s (eing part of a particular soft are distri(ution. If t%e program is e'tracted from t%at distri(ution and used or distri(uted it%in t%e terms of t%e program0s license* all parties to %om t%e program is redistri(uted s%ould %ave t%e same rig%ts as t%ose t%at are granted in con4unction distri(ution. 6. 2icense 4ust Not Restrict Other Software -%e license must not place restrictions on ot%er soft are t%at is distri(uted along t%e same medium must (e open)source soft are. 17. 2icense 4ust 5e Techno"o()8Neutra" No provision of t%e license may (e predicated on any individual tec%nology or style of interface. 1.1.1 Need of Open Sources /e reasons %y you need an Open Source Strategy are:
3 Sree Sakthi Engineering College

%om t%e program is redistri(uted

it%out t%e need for e'ecution of an additional license (y t%ose parties.

it% t%e original soft are

it% t%e

licensed soft are. /or e'ample* t%e license must not insist t%at all ot%er programs distri(uted on

6. Reduce dependenc) on c"osed source %endors. Stop (eing dragged t%roug% constant product upgrades t%at you are forced to do to stay on a supported version of t%e product. 7. 9our annua" bud(et does not &eep up with increases in software -aintenance costs and increased costs of e-p"o)ee hea"th care. 8our (udget remains flat* you (oug%t five ne tools last year it% ne annual costs in t%e range of 69)7:; of t%e original purc%ase price for 3gold support3* and your employees0 %ealt% care costs s%ot up 7<; again. =. 4ore access to too"s. 8ou can get your %ands a variety of development and testing tools* pro4ect and portfolio management tools* net or+ monitoring* security* content management* etc. (ac+s. >. Tr) before )ou bu). Are you getting ready to invest in SOA* ?#"* or @$"A 5%y not do a prototype familiar it%out spending %uge sums of moneyA /irst of all* it allo s you to get %en you go t%roug% t%e vendor it% t%e tools so you can (e educated it%out %aving to as+ t%e (oss man for a fe %undred t%ousand green

evaluation process. Second of all* you mig%t find t%at t%e tool can do t%e 4o( and you don0t need to loc+ yourself in to anot%er vendor. <. .reat support and a #':1 on"ine co--unit) that responds ;uic&"). &espite t%e myt%s t%at you can0t get support for open source soft are* t%e leading communities provide support far superior to most closed source vendors. "ost communities %ave a great +no ledge(ase or i+i for self service support. 8ou can also post a ,uestion and one of orld ill most li+ely respond in t%e %undreds of community mem(ers t%roug%out t%e

minutes. "a+e sure you c%ose soft are it% strong community (ac+ing. B. *ccess to source code and the abi"it) to custo-i<e if )ou desire. 8ou can see t%e code* c%ange t%e code* and even su(mit your en%ancements andCor fi'es (ac+ to t%e community to (e peer revie ed and possi(ly added to t%e ne't (uild. No longer do you need to in t%e fall of 7::D. E. .reat ne(otiatin( power when dea"in( with c"osed source %endors. -ired of vendors pus%ing you around (ecause you don0t %ave optionsA I onder if companies li+e
4 Sree Sakthi Engineering College

ait

for a vendor roadmap t%at doesn0t %ave t%e feature you need until t%eir @'cali(ur release

"icrosoft ould (e more illing to (e fle'i(le it% t%eir pricing if you %ave 7: des+tops running U(untu as an alternative des+top pilot initiative. 9. Feature set is not b"oated and is dri%en b) co""aboration a-on(st the co--unit). -ired of products t%at consume %uge amounts of memory and $#U po er for t%e 7::: eye candy features t%at you ill never useA 5it% open source soft are* most features are driven (y community demand. $losed vendors %ave to create one more feature t%en t%eir competitors to get t%e edge in t%e mar+etplace.
D. 5u( fi=es are i-p"e-ented faster than c"osed source %endors. Actually* many (ugs

are fi'ed (y t%e community (efore t%ey are even reported (y t%e users. 1.1.# *d%anta(es of Open Sources Open source soft are can %ave a ma4or impact on your entire organi.ation. -%ere are several advantages of using open source soft are. -%e follo ing are a list of t%e advantages of opting for open source soft are. 1. 2esser hardware costs Since Linu' and open source solutions are easily porta(le and compressed* it ta+es lesser %ard are po er to carry out t%e same tas+s servers* suc% as* Solaris* 5indo s or #. >i(h8;ua"it) software Open source soft are is mostly %ig%),uality soft are. 5%en you use t%e open source soft are* t%e source code is availa(le. "ost open source soft are are an ideal c%oice for organi.ations. $. No %endor "oc&8in I- managers in organi.ations face constant frustration %en dealing it% vendor loc+) ins0. Lac+ of porta(ility* e'pensive license fees and ina(ility to customi.e soft are are some of t%e ot%er disadvantages. Using open source soft are gives you more freedom and you can effectively address all t%ese disadvantages. '. Inte(rated -ana(e-ent
5 Sree Sakthi Engineering College

%en compared to t%e %ard are po er it ta+es on

or+stations. 5it% t%is less %ard are po er advantage*

you can even use c%eaper or older %ard are and still get t%e desired results.

ell)designed. Open

source soft are can also (e efficiently used in coding. -%ese reasons ma+e open source soft are

?y using open source soft are* you can (enefit from integrated management. Open source soft are uses tec%nologies* suc% as* common information model 1$I"2 and com(ine server* application* service and in efficient administration. ,. Si-p"e "icense -ana(e-ent 5%en you use open source soft are* you ould no longer need to orry a(out licenses. Open source soft are ena(les you to install it several times and also use it from any location. 8ou ill (e free from monitoring* trac+ing or counting license compliance. or+station management. -%is integration e( (ased ould result enterprise management 15?@"2. -%ese %ig%)end tec%nologies ena(le you to integrate and

/. 2ower software costs Using open source soft are can %elp you minimi.e your e'penses. 8ou can save on licensing fees and maintenance fees. -%e only e'penses t%at you e'penditure for documentation* media and support. 1. *bundant support 8ou ill get ample support %en you use open source soft are. Open source support is mostly freely availa(le and can (e easily accessed t%roug% online communities. -%ere are also many soft are companies t%at provide free online %elp and also varied levels of paid support. "ost organi.ation support. 3. Sca"in( and conso"idatin( Linu' and open source soft are can (e easily scaled. 5it% varied options for clustering* load (alancing and open source applications* suc% as email and data(ase* you can ena(le your organi.ation to eit%er scale up and ac%ieve %ig%er gro t% or consolidate and ac%ieve more less. 6. 0%o"%in( software As mentioned* some Open Source soft are pro4ects can %ave %uge communities of programmers involved* allo ing for t%e rapid implementation of ne features and security fi'es.
6 Sree Sakthi Engineering College

ould encounter

ould (e

%o create open source soft are solutions also provide maintenance and

it%

-%e communities of users and programmers are also invalua(le resources for as+ing ,uestions relating to trou(les%ooting and suggesting en%ancements. 17. Rapid debu((in(? rapid further de%e"op-ent ?ecause t%e source code is open* t%e developerCproducer does not 4ust receive feed(ac+ on any errors or pro(lems* or proposals for ne do n to t%e code level functions* (ut feed(ac+ reports t%at can specify %at s%ould (e done it is t%erefore far simpler for t%e producer to

implement c%anges on t%e (asis of feed(ac+ reports since t%ese often say precisely %at program c%anges must (e made and also any errors in t%e original source code may (e corrected (y t%e person %o detects t%e error it%out %aving to ait for t%e original programmer. 11. *%oidin( "oc&8in to one supp"ier It is o(viously great to %ave one soft are supplier to turn to per%aps to provide services connected it% t%e soft are* suc% as installation assistance* courses* operation* support and more* and you %ave someone to ring if you need %elp or information concerning t%e soft are. 1#. 0as) inte(ration and interaction Open Source code means t%at it is relatively simple to adapt programs so t%at t%ey can or+ it% eac% ot%er (ecause you can see from t%e source codes %o a program Ft%in+sF and %o you s%ould approac% it to s%are or e'c%ange data. Disad%anta(es of usin( Open Source -%ere0s a flip side to everyt%ing* and in t%e case of Open Source soft are it all (oils do n to t%e old saying of 3t%ere0s no suc% t%ing as a free lunc%3. "ost of t%e disadvantages only apply if you0re not some %at code)savvy and illing to get your %ands dirty: 6. "ostly used commercial applications. 7. #ro4ects can die =. Support issues 1.1.$ *pp"ication of Open Sources.

7 Sree Sakthi Engineering College

Open source tec%nology ma+es a real (usiness sense. It is free and of very %ig% ,uality* also it is often more effective t%an most of t%e products availa(le commercially and non)commercial. Some applications listed (elo : 6. Accounting 7. $ontent "anagement Systems =. $G" 1$ustomer Gelations%ip "anagement2 >. &es+top @nvironmentsC S%ell replacements <. @mail $lients B. @ncoding* $onversion H Gipping -ools E. @G# 9. /ile s%aring H /-# D. Grap%ics)&esign H "odeling -ools 6:. "essengers H $ommunication $lients 66. #ro4ect "anagement 67. Geporting -ools 6=. GSS 6>. 5e( ?ro sers

S.No 6 7 = > < B E 9 D 6:

*pp"ication $loud management ecommerce Geporting -ools @nterprise $ontent "anagement* 5e( $ontent "anagement &ata ?ac+up C Gecovery @G# and $G" Office #roductivity G&?"S Soft are &evelopment -ools for $* $II Server and client Linu' distri(ution

Open Source Too"s A(i,uo Avactis Actuate Alfresco ?acula $ompiere Lotus Symp%ony Ingres &ata(ase Sun Studio U(untu
8 Sree Sakthi Engineering College

Table - List of Commercial Open Source Applications with tools

1.#. Open source operatin( s)ste-s@ 2INUA@ 1.#.1 Introduction

9 Sree Sakthi Engineering College

Linu' is an Operating System t%at UNIX system t%at

as first created at t%e University of Jelsin+i in as or+ing on a (udget* and %is

/inland (y a young student named Linus -orvalds. At t%is time t%e student as running on an e'pensive platform. ?ecause of %is lo

need to or+ at %ome* %e decided to create a copy of t%e UNIX system in order to run it on a less e'pensive platform* suc% as an I?" #$. Je (egan %is or+ in 6DD6 %en %e released version :.:7 and or+ed steadily until 6DD> %en version 6.: of t%e Linu' !ernel as released. -%e current full)featured version at t%is time is 7.7.XK released Lanuary 7<* 6DDD* and development continues. Reasons to use 2inu= Confi(urabi"it) Linu' distri(utions give t%e user full access to configure 4ust a(out any aspect of t%eir system. Options range from t%e simple and straig%tfor ard. Con%enience 5%ile Linu' ta+es some effort to get set up* once it is set up* it is surprisingly lo ) maintenance. Stabi"it) Linu' is (ased on t%e UNIX +ernel. It provides preemptive multitas+ing and protected memory. Co--unit) Linu' is part of t%e greater open)source community. -%is consists of t%ousands of developers and many more users developer (ase is also a support (ase. FreedoLinu' is free. -%is means more t%an 4ust costing not%ing. -%is means t%at you are allo ed to do %atever you ant to it% t%e soft are. -%is is %y Ged%at* "andra+e* and Suse are all allo ed to sell t%eir o n distri(utions of Linu' 1.#.# .enera" O%er%iew 1.#.#.1 The 2inu= Berne"
10 Sree Sakthi Engineering College

orld) ide

%o support open soft are. -%is user and

-%e Linu' !ernel is an operating system*

%ic% runs on a

ide variety of %ard are and

for a variety of purposes. Linu' is capa(le of running on devices as simple as a rist atc%* or a cell p%one* (ut it can also run on a %ome computer using* for e'ample Intel* or A"& processors* and its even capa(le of running on %ig% end servers using Sun Sparc $#UMs or I?" po er #$ processors. Some Linu' distroMs can only run one processor* %ile ot%ers can run many at once. -%e Linu' +ernel is an operating system +ernel used (y t%e Linu' family of Uni')li+e operating systems. It is one of t%e most prominent e'amples of free and open source soft are. -%e Linu' +ernel as initially conceived and created (y Finnish co-puter science student 2inus Tor%a"ds in 1661. 2inu= rapid") accu-u"ated de%e"opers and users who adopted code fro- other free software proCects for use with the new operatin( s)ste-. The 2inu= &erne" has recei%ed contributions fro- thousands of pro(ra--ers. 4an) 2inu= distributions ha%e been re"eased based upon the 2inu= &erne". 1.#.#.# !roperties of 2inu= 2inu= !ros A lot of t%e advantages of Linu' are a conse,uence of Linu'0 origins* deeply rooted in UNIX* e'cept for t%e first advantage* of course:

Linu' is free: Linu' is porta(le to any %ard are platform: Linu' as made to +eep on running: Linu' is secure and versatile: Linu' is scala(le: -%e Linu' OS and most Linu' applications %ave very s%ort de(ug)times: -%ere are far too many different distri(utions: Linu' is not very user friendly and confusing for (eginners: Is an Open Source product trust ort%yA

2inu= Cons

1.#.#.$ 2inu= %s. Windows -opic Linu' 5indo s


11 Sree Sakthi Engineering College

-%e ma4ority of Linu' variants are !rice t%an 5indo s. -%e ma4ority of Linu' variants and Re"iabi"it) versions are notoriously relia(le and can often run for mont%s and years it%out needing to (e re(ooted. Linu' %as a large variety of availa(le Software soft are programs* utilities* and games. Jo ever* 5indo s %as a muc% larger selection of availa(le soft are. "any of t%e availa(le soft are programs* utilities* and games availa(le on Linu' Software Cost are free are andCor open source. @ven suc% comple' programs suc% as Gimp* OpenOffice* StarOffice* and ine are availa(le for free or at a lo cost. Linu' companies and %ard are manufacturers %ave made great advancements in %ard are support for >ardware Linu' and today Linu' ill support most %ard are devices. Jo ever* many companies still do not offer drivers or support for t%eir %ard are in Linu'. Securit) Linu' is and %as al ays (een a very secure operating system. Alt%oug% it still

"icrosoft 5indo s can run (et een license copy. Alt%oug% "icrosoft 5indo s %as made great improvements in relia(ility over t%e last fe versions of 5indo s* it still cannot matc% t%e relia(ility of Linu'. ?ecause of t%e large amount of "icrosoft 5indo s users* t%ere is a muc% larger selection of availa(le soft are programs* utilities* and games for 5indo s. Alt%oug% 5indo s does %ave soft are programs* utilities* and games for free* t%e ma4ority of t%e programs ill cost any %ere (et een N7:.:: ) N7::.::I US dollars per copy. ?ecause of t%e amount of "icrosoft 5indo s users and t%e (roader driver support* 5indo s %as a muc% larger support for %ard are devices and a good ma4ority of %ard are manufacturers ill support t%eir products in "icrosoft 5indo s. Alt%oug% "icrosoft %as made great improvements over t%e years it%
12 Sree Sakthi Engineering College

availa(le for free or at a muc% lo er price N7:.:: ) N6<:.:: US dollars per eac%

security on t%eir operating system* t%eir can (e attac+ed %en compared to 5indo s* it muc% more secure. operating system continues to (e t%e most vulnera(le to viruses and ot%er attac+s. "any of t%e Linu' variants and many Open Source Linu' programs are open source and ena(le users to customi.e or modify t%e code %o ever t%ey is% to. Alt%oug% it may (e more difficult to find users familiar it% all Linu' variants* Support documentation and %elp availa(le for Linu'. 1.#.$ Berne" 4ode and user -ode A +ernel is t%e main program or component of an operating system* it0s t%e t%ing t%at does all t%e or+* and it%out it you %ave no operating system. Linu' is actually not%ing more operating system is usually referred to as GNUCLinu'. t%an a +ernelK t%e programs t%at ma+e up t%e rest of t%e operating system are generally GNU soft are* so t%e entire User mode is t%e normal mode of operating for programs. 5e( (ro sers* calculators* etc. ill all (e in user mode. -%ey don0t interact directly instructions on ot%er %and* is %ere programs communicate directly it% t%e +ernel* instead* t%ey 4ust give it% t%e +ernel. A good e'ample of t%is it% t%e +ernel* %at needs to (e done* and t%e +ernel ta+es care of t%e rest. !ernel mode* on t%e "icrosoft 5indo s is not open source and t%e ma4ority of 5indo s programs are not open source. "icrosoft 5indo s includes its o n %elp section* %as vast amount of %elp* as ell as (oo+s on eac% of t%e versions of 5indo s.

t%ere are vast amounts of availa(le online availa(le online documentation and

ould (e device drivers. A device driver must tell t%e +ernel e'actly %o to interact it% a piece of %ard are* so it must (e run in +ernel mode. ?ecause of t%is close interaction crucial t%at drivers are properly de(ugged (efore (eing released to t%e pu(lic. A process can run in t o modes:
13 Sree Sakthi Engineering College

t%e +ernel is also a lot more vulnera(le to programs running in t%is mode* so it (ecomes %ig%ly

6.User "ode. 7.!ernel "ode. 1.User 4ode: A mode of t%e $#U %en running a program. In t%is mode* t%e user process %as no access to t%e memory locations used (y t%e +ernel. 5%en a program is running in User "ode* it cannot directly access t%e +ernel data structures or t%e +ernel programs. -%e +ernel)mode programs run in t%e (ac+ground* ma+ing sure everyt%ing runs smoot%ly ) t%ings li+e printer drivers* display drivers* drivers t%at interface it% t%e monitor* +ey(oard* mouse* etc. -%ese programs all run in suc% a ay t%at you don0t notice t%em. 5%en t%e computer (oots up* 5indo s calls t%e !@GN@L* t%e main +ernel)mode program t%at allo s all t%e ot%er programs to run* even t%e user)mode programs. User mode is t%e normal mode of operating for programs* e( (ro sers etc. -%ey don0t interact directly it% t%e +ernel* instead* t%ey 4ust give instructions on %at needs to (e done* %ere programs and t%e +ernel ta+es care of t%e rest. !ernel mode* on t%e ot%er %and* is communicate directly it% t%e +ernel. A good e'ample of t%is e'actly %o to interact ould (e device drivers. A device driver must tell t%e +ernel it% a piece of %ard are* so it must (e run in +ernel mode. ?ecause of

t%is close interaction it% t%e +ernel* t%e +ernel is also a lot more vulnera(le to programs running in t%is mode* so it (ecomes %ig%ly crucial t%at drivers are properly de(ugged (efore (eing released to t%e pu(lic. -%ese are t%e programs t%at you run %en you ant specific programs ) e.g.* "S #aint* "S 5ord* and $alculator. -%ese are %eavily restricted* as to not cras% t%e system. 5indo s uses memory)protection services offered (y t%e processor to prevent malicious programs from interfering it% t%e rest of t%e system and corrupting it. In User mode* t%e e'ecuting code %as no a(ility to directly access %ard are or reference memory. $ode running in user mode must delegate to system A#Is to access %ard are or memory. &ue to t%e protection afforded (y t%is sort of isolation* cras%es in user mode are al ays recovera(le. "ost of t%e code running on your computer ill e'ecute in user mode.
14 Sree Sakthi Engineering College

#. Berne" 4ode@ A mode of t%e $#U %en running a program. In t%is mode* it is t%e +ernel t%at is running on (e%alf of t%e user process and directly access t%e +ernel data structures or t%e +ernel programs. Once t%e system call returns* t%e $#U s itc%es (ac+ to user mode. -%e +ernel)mode programs run in t%e (ac+ground* ma+ing sure everyt%ing runs smoot%ly ) t%ings li+e printer drivers* display drivers* drivers t%at interface it% t%e monitor* +ey(oard* mouse* etc. -%ese programs all run in suc% a ay t%at you don0t notice t%em. 5%en t%e computer (oots up* 5indo s calls t%e !@GN@L* t%e main +ernel)mode program t%at allo s all t%e ot%er programs to run* even t%e user)mode programs. !ernel mode* also referred to as system mode* is one of t%e t o distinct modes of operation of t%e $#U in Linu'. 5%en t%e $#U is in +ernel mode* it is assumed to (e e'ecuting trusted soft are* and t%us it can e'ecute any instructions and reference any memory addresses 1i.e.* locations in memory2. -%e +ernel 1 %ic% is t%e core of t%e operating system and %as complete control over everyt%ing t%at occurs in t%e system2 is trusted soft are* (ut all ot%er programs are considered untrusted soft are. In t%is mode e'ecuting code %as complete and unrestricted access to t%e underlying %ard are. It can e'ecute any $#U instruction and reference any memory address. !ernel mode is generally reserved for t%e lo est)level* most trusted functions of t%e operating system. $ras%es in +ernel mode are catastrop%icK t%ey ill %alt t%e entire #$. 5%en t%e $#U is in +ernel mode* it is assumed to (e e'ecuting trusted soft are* and t%us it can e'ecute any instructions and reference any memory addresses 1i.e.* locations in memory2. -%e +ernel 1 %ic% is t%e core of t%e operating system and %as complete control over everyt%ing t%at occurs in t%e system2 is trusted soft are* (ut all ot%er programs are considered untrusted soft are. -%us* all user mode soft are must re,uest use of t%e +ernel (y means of a system call in order to perform privileged instructions* suc% as process creation or inputCoutput operations.
15 Sree Sakthi Engineering College

Distin(uish 5etween User 4ode and Berne" 4ode !ernal mode %as %ig%er priority %ile user mode %as lo er priority. !ernal mode %as a(ility to read user mode (ut user mode %as not priority to interface in +ernal mode. 5%en a process is in user space* its system calls are (eing intercepted (y t%e tracing t%read. 5%en it0s in t%e +ernel* it0s not under system call tracing. -%is is t%e distinction (et een user mode and +ernel mode. -%e transition from user mode to +ernel mode is done (y t%e tracing t%read. 5%en a process e'ecutes a system call or receives a signal* t%e tracing t%read forces t%e process to run in t%e +ernel if necessary and continues it it%out system call tracing. 1.#.' !rocess Definition@ A process is an e'ecuting 1i.e.* running2 instance of a program. #rocess are fre,uently referred to as tas+s. #rocess 1process I&* #I&2: All soft are runs it%in an operating system concept +no n as a process. @ac% program running on a system is assigned its o n process I& 1#I&2. Users can easily o(tain a process list 1using -as+ "anager on 5indo s or ps on UNIX2 in order to see %at is running. 1.#.'.1. !rocesses inside out 1.#.'.1.1. 4u"ti8user and -u"ti8tas&in( "ultiuser refers to %aving more t%an 6 person a(le to log into t%e computer and eac% person %ave t%eir o n settings 1(oo+mar+* des+top* t%emes* etc2 "ultitas+ing is t%e a(ility of t%e computer to do more t%an 6 t%ing 1program2 at a time. -%ere as a time %en you could not surf* type in ord and listen to music on your computer all at one time. 1.#.'.1.#. !rocess t)pes 1.#.'.1.#.1. Interacti%e processes

16 Sree Sakthi Engineering College

Interactive processes are initiali.ed and controlled t%roug% a terminal session. In ot%er ords* t%ere %as to (e someone connected to t%e system to start t%ese processesK t%ey are not started automatically as part of t%e system functions Gunning a process in t%e (ac+ground is only useful for programs t%at don0t need user input 1via t%e s%ell2.#utting a 4o( in t%e (ac+ground is typically done %en e'ecution of a 4o( is e'pected to ta+e a long time. In t%e e'ample* using grap%ical mode* e open an e'tra terminal indo from t%e e'isting one:

aravind:OP =ter- & Q6R 7B<<9 aravind:OP Cobs Q6RI Gunning 'term H

Controlling processes

part ofD co--and re(u"arEco--and co--and & Cobs Ctr"IF

4eanin( Guns t%is command in t%e foreground. Gun t%is command in t%e (ac+ground 1release t%e terminal2 S%o commands running in t%e (ac+ground. Suspend 1stop* (ut not ,uit2 a process running in t%e foreground 1suspend2.

Ctr"IC b( f( &i""

Interrupt 1terminate and ,uit2 a process running in t%e foreground. Geactivate a suspended program in t%e (ac+ground. #uts t%e 4o( (ac+ in t%e foreground. @nd a process
17 Sree Sakthi Engineering College

1.#.'.1.#.#. *uto-atic processes Automatic or (atc% processes are not connected to a terminal. Gat%er* t%ese are tas+s t%at can (e ,ueued into a spooler area* %ere t%ey ait to (e e'ecuted on a /I/O 1first)in* first)out2 (asis. Suc% tas+s can (e e'ecuted using one of t o criteria:

At a certain date and time: done using t%e at command. At times %en t%e total system load is lo enoug% to accept e'tra 4o(s: done using t%e batch command.

1.#.'.1.#.$. Dae-ons A daemon process %as no controlling terminal. It cannot open CdevCtty. "ost daemons tend to last a long time* (e o ned (y root* and do somet%ing useful. A daemon is 4ust a process t%at runs in t%e (ac+ground* usually aiting for somet%ing to %appen t%at it is capa(le of or+ing it%* li+e a printer daemon is aiting for print commands. &aemons are server processes t%at run continuously. "ost of t%e time* t%ey are initiali.ed at system startup and t%en ait in t%e (ac+ground until t%eir service is re,uired. 1.#.'.1.$. !rocess attributes A process %as a series of c%aracteristics* %ic% can (e vie ed it% t%e ps command: -%e process I& or #I&: a uni,ue identification num(er used to refer to t%e process. -%e parent process I& or ##I&: t%e num(er of t%e process 1#I&2 t%at started t%is process. Nice num(er: t%e degree of friendliness of t%is process to ard ot%er processes 1not to (e confused it% process priority* %ic% is calculated (ased on t%is nice num(er and recent $#U usage of t%e process2. -erminal or --8: terminal to %ic% t%e process is connected. User name of t%e real and effective user 1GUI& and @UI&2: t%e o ner of t%e process. Geal and effective group o ner 1GGI& and @GI&2: -%e real group o ner of a process is t%e primary group of t%e user %o started t%e process. 1.#.'.1.'. Disp"a)in( process infor-ation

18 Sree Sakthi Engineering College

-%e ps command is one of t%e tools for visuali.ing processes. -%is command %as several options %ic% can (e com(ined to display different process attri(utes.5it% no options specified* ps only gives information a(out t%e current s%ell and eventual processes: aravind:OP ps #I& --8 -I"@ $"& >7>< ptsCE :::::::: (as% <=6> ptsCE :::::::: ps

1.#.'.1.,. 2ife and death of a process 1.#.'.1.,.1. !rocess creation A ne process is created (ecause an e'isting process ma+es an e'act copy of itself. -%is c%ild process %as t%e same environment as its parent* only t%e process I& num(er is different. -%is procedure is called forking. After t%e for+ing process* t%e address space of t%e c%ild process is over ritten it% t%e ne process data. -%is is done t%roug% an exec call to t%e system. 1.#.'.1.,.#. 0ndin( processes 5%en a process ends normally 1it is not +illed or ot%er ise une'pectedly interrupted2* t%e program returns its exit status to t%e parent. -%is e'it status is a num(er returned (y t%e program providing t%e results of t%e program0s e'ecution. 1.#.'.1.,.$. Si(na"s #rocesses end (ecause t%ey receive a signal. -%ere are multiple signals t%at you can send to a process. Use t%e &i"" command to send a signal to a process. -%e command &i"" 8" s%o s a list of signals. "ost signals are for internal use (y t%e system* or for programmers %en t%ey rite code. As a user* you ill need t%e follo ing signals: Co--on si(na"s Si(na" na-e SIG-@G" SIGINSIG!ILL SIGJU# Si(na" nu-ber 1, # 6 1 4eanin( -erminate t%e process in an orderly ay. Interrupt t%e process. A process can ignore t%is signal. Interrupt t%e process. A process can not ignore t%is signal. /or daemons: reread t%e configuration file.
19 Sree Sakthi Engineering College

1.#.'.#. 5oot process? Init and shutdown 1.#.'.#.1. !C 5oot and 2inu= Init !rocess@ ?IOS: -%e ?asic InputCOutput System is t%e lo est level interface (et een t%e computer and perip%erals. -%e ?IOS performs integrity c%ec+s on memory and see+s instructions on t%e "aster ?oor Gecord 1"?G2 on t%e floppy drive or %ard drive. -%e "?G points to t%e (oot loader 1GGU? or LILO: Linu' (oot loader2. ?oot loader 1GGU? or LILO2 ill t%en as+ for t%e OS la(el %ic% ill identify %ic% +ernel to run and %ere it is located 1%ard drive and partition specified2. -%e installation process re,uires to creationCidentification of partitions and %ere to install t%e OS. GGU?CLILO are also configured during t%is process. -%e (oot loader t%en loads t%e Linu' operating system. -%e first t%ing t%e +ernel does is to e'ecute init program. Init is t%e rootCparent of all processes e'ecuting on Linu'. -%e first processes t%at init starts is a script CetcCrc.dCrc.sysinit ?ased on t%e appropriate run)level* scripts are e'ecuted to start various processes to run t%e system and ma+e it functional. One of t%e most po erful aspects of Linu' concerns its open met%od of starting and stopping t%e operating system* %ere it loads specified programs using t%eir particular configurations* permits you to c%ange t%ose configurations to control t%e (oot process* and s%uts do n in a graceful and organi.ed ay. ?eyond t%e ,uestion of controlling t%e (oot or s%utdo n process* t%e open nature of Linu' ma+es it muc% easier to determine t%e e'act source of most pro(lems associated every(ody it% starting up or s%utting do n your system. A (asic understanding of t%is process is ,uite (eneficial to %o uses a Linu' system.A lot of Linu' systems use "i"o* t%e LInu' LOader for ill only discuss GGU?* %o ever* %ic% is easier to use and (ooting operating systems. 5e more fle'i(le. Init@

20 Sree Sakthi Engineering College

-%e +ernel* once it is loaded* finds init in s(in and e'ecutes it.5%en init starts* it (ecomes t%e parent or grandparent of all of t%e processes t%at start up automatically on your Linu' system. -%e first t%ing init does* is reading its initiali.ation file* CetcCinitta(. -%is instructs init to read an initial configuration script for t%e environment* %ic% sets t%e pat%* starts s apping* c%ec+s t%e file systems* and so on. ?asically* t%is step ta+es care of everyt%ing t%at your system needs to %ave done at system initiali.ation: setting t%e cloc+* initiali.ing serial ports and so fort%. -%en init continues to read t%e CetcCinitta( file* %ic% descri(es %o t%e system s%ould (e set up in eac% run level and sets t%e default run level. A run level is a configuration of processes. All UNIX)li+e systems can (e run in different process configurations* suc% as t%e single user mode* %ic% is referred to as run level 6 or run level S 1or s2. In t%is mode* only t%e system it%out ris+s of e don0t need to offer user administrator can connect to t%e system. It is used to perform maintenance tas+s damaging t%e system or user data. Naturally* in t%is configuration services* so t%ey t%e system. Use t%e who to c%ec+ %at your current run level is:
aravind@home:~> who -r run-level 2 2010-10-17 23:22 last=S

ill all (e disa(led. Anot%er run level is t%e re(oot run level* or run level B*

%ic% s%uts do n all running services according to t%e appropriate procedures and t%en restarts

Init run "e%e"s Availa(le run levels are generally descri(ed in CetcCinitta(* %ic% is partially s%o n (elo : S S initta( -%is file descri(es %o t%e INI- process s%ould set up S t%e system in a certain run)level. S &efault run level. -%e run levels are: S : ) %alt 1&o NO- set initdefault to t%is2 S 6 ) Single user mode
21 Sree Sakthi Engineering College

S 7 ) "ultiuser* it%out N/SS 1-%e same as =* if you do not %ave net or+ing2 S = ) /ull multiuser mode S > ) unused S < ) X66 S B ) re(oot 1&o NO- set initdefault to t%is2 S id:<:initdefault: T))cut))P 1.#., *d%anced Concepts Sc%eduling #ersonalities $loning Signals &evelopment it% Linu' 1.#./ Schedu"in(
A Linux s ste! "an ha#e a lot to su$$er $ro!% &ut it usuall su$$ers onl 'uring o$$i"e hours. (hether in an o$$i"e en#iron!ent% a ser#er roo! or at ho!e% !ost Linux s ste!s are )ust i'ling a*a 'uring the !orning% the e#ening% the nights an' *eeken's. +sing this i'le ti!e "an &e a lot "hea,er than &u ing those !a"hines ou-' a&solutel nee' i$ ou *ant e#er thing 'one at the sa!e ti!e. .here are three t ,es o$ 'ela e' exe"ution/ (aiting a little *hile an' then resu!ing )o& exe"ution% using the sleep "o!!an'. Exe"ution ti!e 'e,en's on the s ste! ti!e at the !o!ent o$ su&!ission. 0unning a "o!!an' at a s,e"i$ie' ti!e% using the at "o!!an'. Exe"ution o$ the )o&1s2 'e,en's on s ste! ti!e% not the ti!e o$ su&!ission. 0egularl running a "o!!an' on a !onthl % *eekl % 'ail or hourl &asis%

using the cron $a"ilities.

1.#./.1 The at co--and -%e at command e'ecutes commands at a given time* using your default s%ell unless you tell t%e command.-%e options to at are rat%er user)friendly* e'amples (elo :
22 Sree Sakthi Engineering College

%ic% is demonstrated in t%e

aravindU%ome:OP at to-orrow G # da)s arning: commands ill (e e'ecuted using 1in order2 a2 NSJ@LL (2 login s%ell c2 C(inCs% atP cat reports H -ai" -)bossI-)co-pan) atP T@O-P 4o( 6 at 7:6:)6:)6B 67:=B
. ,ing Ctrl3D 4uits the at utilit an' generates the 5E6.5 !essage. +ser aravind 'oes a strange thing here "o!&ining t*o "o!!an's

aravindU%ome:OP at 7#$1 arning: commands ill (e e'ecuted using 1in order2 a2 NSJ@LL (2 login s%ell c2 C(inCs% atP cd new8pro(ra-s atP .:confi(ureJ -a&e atP T@O-P 4o( 7 at 7:6:)6:)6> :7::: -%e )m option sends mail to t%e user %en t%e 4o( is done* or e'plains %en a 4o( can0t (e

done. -%ecommand at; lists 4o(sK perform t%is command (efore su(mitting 4o(s in order prevent t%em from starting at t%e same time as ot%ers. 5it% t%e atr- command you can remove sc%eduled 4o(s if you c%ange your mind. -%e at command is used to sc%edule one or more programs for a single e'ecution at some later time. -%ere are actually four client commands: 6. at: Guns commands at specified time 7. at,: Lists pending commands =. atrm: $ancels pending 4o(s
23 Sree Sakthi Engineering College

>. (atc%: Guns commands %en system load permits -%e Linu' at command accepts a num(er of time specifications* considera(ly e'tending t%e #OSIX.7 standard. 1.#./.# Cron and crontab -%e cron system is managed (y t%e cron daemon. It gets information a(out programs and user %as access to t%e system cronta(s* %ic% %en t%ey s%ould run from t%e system0s and users0 cronta( entries. Only t%e root %ile eac% user s%ould only %ave access to %is o n

cronta(s. On some systems 1some2 users may not %ave access to t%e cron facility. At system startup t%e cron daemon searc%es CvarCspoolCcronC for cronta( entries %ic% are named after accounts in CetcCpass d* it searc%es CetcCcron.dC and it searc%es CetcCcronta(* t%en uses t%is information every minute to c%ec+ if t%ere is somet%ing to (e done. It e'ecutes commands as t%e user o ner. S)nta= cronta( Q)eR Q)lR Q)rR QfilenameR )e edit a copy of t%e current user0s cronta( file* or creates an empty file to edit if cronta( does not e'ist. )l )r filename list t%e cronta( file for t%e invo+ing user. remove a user0s cronta( from t%e cronta( -%e filename t%at contains t%e commands to run. %o o ns t%e cronta( file and mails any output of commands to t%e

2ines that can be in the crontab fi"e. minute 1:)<D2* %our 1:)7=2* day of t%e mont% 16)=62* mont% of t%e year 16)672* day of t%e ee+ 1:)B it% :VSunday2. 0=a-p"e@
24 Sree Sakthi Engineering College

cronta( e fields* min %our dayofmont% mont%ofyear dayof ee+ command : 67 6> 7 W @c%o X%aiF

Options 0=p"anation W WC< 7*>*B D)6E Is treated as a ild card. "eaning any possi(le value. Is treated as ever < minutes* %ours* days* or mont%s. Geplacing t%e < it% anot%er numerical value ill c%ange t%is option. -reated as an OG* so if placed in t%e %ours* t%is could mean at 7* >* or B o)cloc+. -reats for any value (et een D and 6E. So if placed in day of mont% t%is ould (e days D t%roug% 6E. Or if put in %ours it ould (e (et een D and <.

1.#./.$ S)ste- Ca""s Re"ated to Schedu"in(@ 5e c%ange t%e sc%eduling parameters (y means of t%e system calls illustrated in t%e -a(le Tab"e 1781@ S)ste- Ca""s Re"ated to Schedu"in( S)ste- Ca"" Description nice1 2 $%ange t%e priority of a conventional process. Get t%e ma'imum priority of a group of conventional getpriority1 2 processes. setpriority1 2 Set t%e priority of a group of conventional processes. sc%edYgetsc%eduler1 2 Get t%e sc%eduling policy of a process. sc%edYsetsc%eduler1 2 Set t%e sc%eduling policy and priority of a process. sc%edYgetparam1 2 Get t%e sc%eduling priority of a process. sc%edYsetparam1 2 Set t%e priority of a process. sc%edYyield1 2 Gelin,uis% t%e processor voluntarily it%out (loc+ing. sc%edYgetY priorityYmin1 2 Get t%e minimum priority value for a policy. sc%edYgetY priorityYma'1 2 Get t%e ma'imum priority value for a policy. sc%edYrrYgetYinterval1 2 Get t%e time ,uantum value for t%e Gound Go(in policy.

25 Sree Sakthi Engineering College

"ost system calls s%o n in t%e ta(le apply to real)time processes* t%us allo ing users to develop real)time applications. 1.#.1 !ersona"ities Linu' supports different e'ecution domains* or personalities* for eac% process. Among ot%er t%ings* e'ecution domains tell Linu' %o ot%er Uni')li+e operating systems. -%is function Ot%er ise* it Na-e personality ) set t%e process e'ecution domain S)nopsis Sinclude TsysCpersonality.%P int personality1unsigned long persona2K Return Ka"ue On success* t%e previous persona is returned. On error* )6 is returned* and errno is set appropriately. 1.#.3 C"onin( "a+ing an image copy of your system dis+ is a great ay to create a (ac+up. 5it% t%e cost of porta(le US? drives at all time lo s* you could +eep a couple around for rotation purposes. If your main drive does cras%* you could (e (ac+ up and running in a matter of minutes. No all t%at0s left is ma+ing t%e actual image copy. -%ere are lots of ays to accomplis% t%is tas+* and e0ll spell a fe of t%em out to %elp you along. -%e (iggest issue it% ma+ing an image copy of your system dis+ is t%at you must (oot from anot%er device to get a true copy. Options include a 3live3 $& or (oota(le US?. 8ou pro(a(ly %ave a copy of your favorite distri(ution0s installation dis+ lying around some %ere* so t%at ould (e an o(vious c%oice. /or our purposes e0ll use t%e U(untu 6:.> distro on a US?
26 Sree Sakthi Engineering College

to map signal num(ers into signal actions. -%e

e'ecution domain system allo s Linu' to provide limited support for (inaries compiled under ill return t%e current personality12 %en persona e,uals :'ffffffff. e'ecution domain

ill ma+e t%e e'ecution domain referenced (y persona t%e ne

of t%e current process.

dis+. -%e second option it% t%e command line.

ould (e to use an actual dis+ duplication distro li+e $lone.illa. -%is

turns out to (e one of t%e easier ays to get t%e 4o( done* especially if you0re not too comforta(le 1.#.3.1 Option One@ 5ootab"e Ubuntu US5 Dis& $reating a (oota(le U(untu US? dis+ is a simple tas+ if you %ave a running system. It0s really not t%at %ard if you don0t eit%er. -%e one t%ing you do need is t%e distri(ution ISO file. 8ou s%ould (e a(le to (oot straig%t from t%e dis+ once you %ave it created. It0s possi(le you mig%t %ave to c%ange your ?IOS setting to allo t%e system to (oot from US?. "any ne er systems 1li+e &ell mac%ines2 %ave an option to (ring up a (oot menu (ac+up image copy. 8ou mig%t Administration list. -%is system and t%eir organi.ation. -%e &is+ Utility provides a num(er of utilities including mount C dismount and format volume. It0s a good idea to go a%ead and format t%e drive if you0re reusing an old 5indo s dis+. G#arted :.<.6 comes standard it% t%e (asic U(untu 6:.:> (oot dis+. It includes an option to copy a partition. Instructions for doing t%e or+ can (e found on eit%er t%e G#arted site or on t%e U(untu forums. -%ere0s also a G#arted Live $& if you ant to go t%at route. ?e prepared to ait a %ile if you c%oose to (ac+up your system to an e'ternal US? as almost four %ours. One really good alternative is drive. -%e total estimated time in our case %en t%e mac%ine first po ers up (y pressing t%e /67 +ey. Once you get t%e system (ooted you0re ready to ma+e your ant to run t%e &is+ Utility found under t%e System C ill give you t%e opportunity to loo+ at t%e dis+s attac%ed to your

to use a dis+ caddy adapter li+e t%e -%ermalta+e ?lac+X S-:::<U. It %as an eSA-A connector t%at speeds up t%e data transfer process tremendously. -%is is a must %ave if you0re t%e type t%at fre,uently tears into systems or (uilds ne ones. 1.#.3.# Option Two@ C"one<i""a $lone.illa is a Linu' distri(ution specifically created for t%e purpose of cloning dis+ drives. It or+s for virtually any file system you can t%in+ of. $lone.illa comes in t o (asic flavors* Live and S@. -%e live version or+s in muc% t%e same ay as t%e U(untu Live US? dis+. 8ou (oot your computer from t%e Live US? and perform t%e dis+ copy operations on any drives connected to t%e computer. $lone.illa uses a num(er of tools along it% a simple menu
27 Sree Sakthi Engineering College

system to %elp guide you t%roug% t%e process. -%e default partition copy tool is #artclone. $lone.illa S@ 1Server @dition2 is meant to (e used to clone dis+s over a net or+. -%e latest release of $lone.illa is 6.7.<.6E and comes in eit%er a &e(ian or U(untu version. 8ou can no do nload an A"&B> version %ic% includes support for B>)(it versions of all t%e applications and t%e imaging of large partitions. All t%e applications %ave (een updated to t%e latest versions along it% t%e 7.B.=7)67 version of t%e Linu' +ernel. -%e %ardest part of using $lone.illa to image your %ard drives is ma+ing sure you +no %ic% drive is t%e master and %ic% drive ill (e your copy. $lone.illa also ta+es care of copying t%e "aster ?oot Gecord 1"?G2 %ile accomplis%ing t%e same tas+ it% t%e U(untu Live $& met%od re,uires some command line magic. 1.#.3.$ Option Three@ dd If you0re a command line i.ard* you could al ays use t%e dd command. -%e command to image a drive it% dd ould (e somet%ing li+e t%e follo ing: S dd if=/dev/sda of=/dev/sdb -%is assumes t%at CdevCsda is t%e drive you is% to copy and CdevCsd( is t%e target drive. 8ou0ll find t%is met%od to (e a(out t%e same speed as t%e G#arted met%od mentioned in Option One a(ove. It really doesn0t matter %ic% met%od you c%oose. -%e important t%ing is t%at you do some +ind of system (ac+up. $omputers do fail from time to time* and it seems to (e 4ust at t%e time %en you can least afford it. Save yourself some grief do n t%e road and go (ac+up your system no . Go a%ead* e0ll ait. 1.#.6 Si(na"s A signal is an event generated (y Linu' in response to some condition* %ic% may cause a process to ta+e some action %en it receives t%e signal. XGaiseF is t%e term t%at indicates t%e generation of a signal. X$atc%F is t%e term to indicate t%e receipt of a signal. Introduced in UNIX systems to simplify I#$. Used (y t%e +ernel to notify processes of system @vents. A signal is a s%ort message sent to a process* or group of processes* containing t%e num(er identifying t%e signal.#OSIX.> defines iCf for ,ueuing H ordering G- signals Linu' supports =6 non)real)time signals.
28 Sree Sakthi Engineering College

C arguments.

#rocesses end (ecause t%ey receive a signal. -%ere are multiple signals t%at you can send to a process. Use t%e &i"" command to send a signal to a process. -%e command &i"" 8" s%o s a list of signals. "ost signals are for internal use (y t%e system or for programmers rite code. 1.#.6.1 Sendin( si(na"s A program can signal a different program using t%e +ill12 system call it% prototype int +ill1pidYt pid* int sig2K -%is ill send t%e signal it% num(er sig to t%e process it% process I& pid. Signal num(ers are small positive integers. 1/or t%e definitions on your mac%ine* try CusrCincludeC(itsCsignum.%. Note t%at t%ese definitions depend on OS and arc%itecture.2 A user can send a signal from t%e command line using t%e +ill command. $ommon uses are +ill )D N to +ill t%e process it% pid N* or +ill )6 N to force process N 1may(e init or inetd2 to reread its configuration file. $ertain user actions ill ma+e t%e +ernel send a signal to a process or group of processes: typing t%e interrupt c%aracter 1pro(a(ly $trl)$2 causes SIGIN- to (e sent* typing t%e ,uit c%aracter 1pro(a(ly $trl)Z2 sends SIG[UI-* %anging up t%e p%one 1modem2 sends SIGJU#* typing t%e stop c%aracter 1pro(a(ly $trl)\2 sends SIGS-O#. $ertain program actions ill ma+e t%e +ernel send a signal to t%at process: for an illegal instruction one gets SIGILL* for accessing non e'isting memory one gets SIGS@G]* for riting to a pipe %ile no(ody is listening anymore on t%e ot%er side one gets SIG#I#@* for reading from t%e terminal %ile in t%e (ac+ground one gets SIG--IN* etc. 1.#.6.# Recei%in( si(na"s 5%en a process receives a signal* a default action %appens* unless t%e process %as arranged to %andle t%e signal. /or t%e list of signals and t%e corresponding default actions* see signal1E2. /or e'ample* (y default SIGJU#* SIGIN-* SIG!ILL ill +ill t%e processK SIG[UIill stop t%e processK ill +ill t%e process and force a core dumpK SIGS-O#* SIG--IN SIG$ON- ill continue a stopped processK SIG$JL& ill (e ignored. -raditionally* one sets up a %andler for t%e signal using t%e signal system call it% prototype typedef void 1Wsig%andlerYt21int2K
29 Sree Sakthi Engineering College

%en t%ey

sig%andlerYt signal1int sig* sig%andlerYt %andler2K -%is sets up t%e routine handler() as %andler for signals default action and ignoring* respectively. 5%en a signal arrives* t%e process is interrupted* t%e current registers are saved* and t%e signal %andler is invo+ed. 5%en t%e signal %andler returns* t%e interrupted activity is continued. It is difficult to do interesting t%ings in a signal %andler* (ecause t%e process can (e interrupted in an ar(itrary place* data structures can (e in ar(itrary state* etc. -%e t%ree most common t%ings to do in a signal %andler are 1i2 set a flag varia(le and return immediately* and 1ii2 1messy2 t%ro a ay all t%e program 1.#.6.$ 5"oc&in( si(na"s @ac% process %as a list 1(itmas+2 of currently (loc+ed signals. 5%en a signal is (loc+ed* it is not delivered 1t%at is* no signal %andling routine is called2* (ut remains pending. -%e sigprocmas+ 12 system call serves to c%ange t%e list of (loc+ed signals. -%e sigpending 12 system call reveals %at signals are 1(loc+ed and2 pending. -%e sigsuspend 12 system call suspends t%e calling process until a specified signal is received. Linu' $ommon Signals are: Si(na" na-e SIGJU# SIGINSIG[UISIGILL SIG-GA# SIGIOSIG?US SIG/#@ Si(na" nu-ber 6 7 = > < B E 9 4eanin( Jangup 1#OSIX2 -erminal interrupt 1ANSI2 -erminal ,uit 1#OSIX2 Illegal instruction 1ANSI2 -race trap 1#OSIX2 IO- -rap 1>.7 ?S&2 ?US error 1>.7 ?S&2 /loating point e'ception
30 Sree Sakthi Engineering College

it% num(er sig. -%e return

value is 1t%e address of2 t%e old %andler. -%e special values SIGY&/L and SIGYIGN denote t%e

as doing* and restart at some convenient point* per%aps t%e main

command loop or so* and 1iii2 clean up and e'it.

1ANSI2 SIG!ILL SIGUSG6 1.#.17 De%e"op-ent with 2inu=. -%e follo ing areas are Linu' development 6. $ompilers 7. &evelopment -ools =. I&@: Integrated &evelopment @nvironment >. "emory &e(ugging -ools <. Soft are &esign 1. Co-pi"ers A compiler t%at allo s a computer program anot%er type. ritten on one type of computer to (e used on D 6: !ill1can0t (e caug%t or ignored2 1#OSIX2 User defined signal 6 1#OSIX2

2an(ua(e $C$IIC/OG-GAN Lava $S A&A LIS# $o(ol #ascal #. De%e"op-ent Too"s


C++:

2inu= Co-pi"er GNU $ compiler man page 1gcc2 GNU $II compiler man page 1gII2 gc4 ) GNU LA]A compiler. Ximian: "ONO GNA$LIS# interpreter* compiler and de(ugger $"U $ommon Lisp -iny$o(ol /ree #ascal

Too"

Description
31 Sree Sakthi Engineering College

cIIfilt S5IG.org

&emangle $II sym(ols Interface compiler for rapper routines testing 3$3 and 3$II3. 5or+s

%ic% run from test scripts for

it% #erl* #yt%on* Gu(y* and -cl and

#araSoft $II -est $: Too" (ison pccts fle' La%a@ Too" +affe Data5ase@ Too" gd(m ?er+eley &? S[Lite.org

allo s scripts to invo+e 3$3 and 3$II3 functions* li(raries* etc. Static source code tester and automated unit test cases.

Description GNU #ro4ect parser generator 1yacc replacement2 #urdue $ompiler)$ompiler 1yaccCle' com(o2 fast le'ical analy.er generator

Description Lava virtual mac%ine

Description -%e GNU data(ase manager. Open Source em(edded data(ase systemCtool+it Open Source em(edded data(ase systemCtool+it

$. ID0@ Inte(rated De%e"op-ent 0n%iron-ent

2an(ua(e @clipse.org

2inu= Co-pi"er I?" open source LA]A and $C$II 1 it% $&- plug)in2 I&@. Included it% /$>. @'tensi(le I&@ consortium ) ?orland* I?"* Ged Jat* Gational. Lots of industry (ac+ing. 1Open Source2 Also see @clipse#lugin$entral.com #lugins availa(le for Su(version S$"* X"L documents* J@X* ... Also see: 8oLinu' $II &evelopment $* $II. 5ritten for G-!CGnome. Solid* simple* intuitive* (ug free I&@
32 Sree Sakthi Engineering College

An4uta

for $C$II development on Linu'. Searc%CInde'ing* edit* compile and $II !&@ I&@ Sun Studio Source Navigator $o(ol #ascal de(ug. Almost no learning curve for t%ose familiar it% I&@0s. $II !&@ I&@ $C$II* /OG-GAN I&@ for Linu'. 1/ree and supported '9B versions2 $C$II* /OG-GAN* $O?OL* -cl* LA]A* asm editor* cross reference tool* class (ro ser and I&@. -iny$o(ol Jome #age /ree #ascal Jome page* documentation and do nload

'. 4e-or) Debu((in(M

2an(ua(e GNU $%ec+er d(malloc fda "$%ec+ 8A"& ,. Software Desi(n Argo ) GUI U"L tool.

2inu= Co-pi"er 5arns of using uninitiali.ed varia(le or memory or unallocated memory. $ malloc* memory* string* and (string /&A provides a tool+it for validating pointers* c%ec+ing for lea+s* gat%ering memory statistics* (ounds c%ec+ing... $C$II memory usage and malloc c%ec+er for '9BClinu'. &etects accesses to uninitiali.ed varia(les* (ad pointers* dou(le frees and memory lea+s. 8et Anot%er "alloc &e(ugger: $C$II

Grap%]i. ) A-- Grap% ]isuali.ation for grap% layout. Used (y dO'ygen for class diagram annotation. Um(rello U"L "odeller I&eogramic ) U"L modeling tool. 1$ommercial product2 &IA: &IA lin+sCtools#oseidon ) 5ritten in LA]A to support all platforms including Linu'. @clipse plugin support. "edoosa ) cpp7dia ) $II to U"L

33 Sree Sakthi Engineering College

UNIT II

O!0N SOURC0 D*T*5*S0

"yS[L: Introduction Setting up account Starting* terminating and riting your O n S[L programs Gecord selection -ec%nology 5or+ing it% strings &ate and -ime Sorting [uery Gesults Generating Summary 5or+ing it% metadata Using se,uences "yS[L and 5e(.

#.1 4)SN2@Introduction
"yS[L is t%e most popular open source S[L data(ase management system 1&?"S2* is developed* distri(uted* and supported (y "yS[L A?. "yS[L A? is a commercial company* founded (y t%e "yS[L developers. A data(ase is a collection of data t%at is organi.ed so t%at its contents can (e easily accessed* managed and updated. "yS[L is a data storage area. In t%is storage area* t%ere are small sections called -a(les. A Gelational &ata(ase "anagement System 1G&?"S2 may (e a &?"S in %ic% data is stored in t%e form of ta(les and t%e relations%ip among t%e data is also stored in -%e data in "yS[L is stored in data(ase o(4ects called ta(les. A ta(le is a collection of related data entries and it consists of columns and ro s. -%e "yS[L data(ase %as (ecome t%e orld0s most popular open source data(ase (ecause of its consistent fast performance* %ig% relia(ility and ease of use. t%e form of ta(les.

#.1.1 *d%anta(es

34 Sree Sakthi Engineering College

o "yS[L is $ross)#latform. It runs on more t%an 7: platforms including Linu'* 5indo s* "ac OS* Solaris* J#)UX* I?" AIX* giving you t%e +ind of fle'i(ility t%at puts you in control. o "yS[L is fast. It is used (y a variety of corporations t%at demand performance and sta(ility. o "yS[L is free. It is Open Source soft are. As suc% you are free to e'amine t%e source code and ma+e any c%anges you is%. As per its G#L license* you are free to redistri(ute t%ose c%anges as long as your soft are is also Open Source. o Gelia(le and easy to use. o "ulti)-%readed multi)user and ro(ust S[L &ata(ase server.

#.1.# Disad%anta(es
o o o o

"issing Su()selects. "yS[L doesn0t yet support t%e Oracle S[L e'tension. &oes not support Stored #rocedures and -riggers. "yS[L doesn0t support vie s.

#.# Settin( up *ccount


In order to provide access t%e "yS[L data(ase you need to create an account to use for connecting to t%e "yS[L server running on a given %ost.Use t%e GGAN- statement to set up t%e "yS[L user account. -%en use t%at account0s name and pass ord to ma+e connections to t%e server.User names* as used (y "yS[L for aut%entication purposes* %ave not%ing to do it% user names 1login names2 as used (y 5indo s or Uni' "yS[L user names can (e up to 6B c%aracters long. "yS[L pass ords %ave not%ing to do t%e name of t%e %ost it% pass ords for logging in to your operating system. $onnecting to a "yS[L server re,uires a username and pass ord. 8ou can also specify %ere t%e server is running. If you don0t specify connection parameters e'plicitly* mysql assumes default values. /or e'ample* if you specify no %ostname* mysql typically assumes t%e server is running on t%e local %ost.
35 Sree Sakthi Engineering College

#.#.1 *ddin( User *ccounts 8ou can create "yS[L accounts in t o ays:
o

?y using statements intended for creating accounts* suc% as $G@A-@ US@G or GGAN-. -%ese statements cause t%e server to ma+e appropriate modifications to t%e grant ta(les. ?y manipulating t%e "yS[L grant ta(les directly U#&A-@* or &@L@-@. it% statements suc% as INS@G-*

#.#.# *ccount 4ana(e-ent State-ents CR0*T0 US0R@ -%e $G@A-@ US@G statement creates ne "yS[L accounts. Synta': $G@A-@ US@G user QI&@N-I/I@& ?8 Q#ASS5OG&R 0pass ord0R Q* user QI&@N-I/I@& ?8 Q#ASS5OG&R 0pass ord0RR ... @'ample: $G@A-@ US@G 0monty0U0local%ost0 I&@N-I/I@& ?8 0someYpass0K DROU! US0R@ -%e &GO# US@G statement removes one or more "yS[L accounts and t%eir privileges. Synta': &GO# US@G user Q* userR ... @'ample: &GO# US@G 04effrey0U0local%ost0K .R*NT @ -%e GGAN- statement ena(les system administrators to grant privileges to "yS[L user accounts. Synta': GGANprivYtype Q1columnYlist2R
36 Sree Sakthi Engineering College

Q* privYtype Q1columnYlist2RR ... ON Qo(4ectYtypeR privYlevel -O user QI&@N-I/I@& ?8 Q#ASS5OG&R 0pass ord0R Q* user QI&@N-I/I@& ?8 Q#ASS5OG&R 0pass ord0RR ... QG@[UIG@ ^NON@ _ sslYoption QQAN&R sslYoptionR ...`R Q5I-J it%Yoption ...R @'ample GGAN- ALL #GI]IL@G@S ON W.W -O 0monty0U0local%ost0 5I-J GGANO#-IONK R0N*40 US0R @ -%e G@NA"@ US@G statement renames e'isting "yS[L accounts. Synta' G@NA"@ US@G oldYuser -O ne Yuser Q* oldYuser -O ne YuserR ... @'ample G@NA"@ US@G 04effrey0U0local%ost0 -O 04eff0U067E.:.:.60K R0KOB0@ -%e G@]O!@ statement ena(les system administrators to revo+e privileges from "yS[L accounts. Synta': G@]O!@ privYtype Q1columnYlist2R Q* privYtype Q1columnYlist2RR ... ON Qo(4ectYtypeR privYlevel /GO" user Q* userR ... G@]O!@ ALL #GI]IL@G@S* GGAN- O#-ION /GO" user Q* userR ... @'ample: G@NA"@ US@G 04effrey0U0local%ost0 -O 04eff0U067E.:.:.60K
37 Sree Sakthi Engineering College

S0T !*SSWORD @ -%e S@- #ASS5OG& statement assigns a pass ord to an e'isting "yS[L user. Synta' S@- #ASS5OG& Q/OG userR V ^ #ASS5OG&10some pass ord02 _ OL&Y#ASS5OG&10some pass ord02 _ 0encrypted pass ord0 ` @'ample: S@- #ASS5OG& /OG 0(o(0U0;.loc.gov0 V #ASS5OG&10new ass02K

#.$ Startin(? ter-inatin( and writin( )our Own SN2 pro(ra-s


#.$.1 Startin( 4)SN2@ o -%e "yS[L server can (e started manually from t%e command line. o -o start t%e -)s;"d server from t%e command line* you s%ould start a console indo 1or X&OS indo F2 and enter t%is command: s%ellP "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysql " o -%e pat% to -)s;"d may vary depending on t%e install location of "yS[L on your system. #.$.1.1 2o(in o -o start t%e mysql program* type myql at your command)line prompt. o If mysqlstarts up correctly* you0ll see a s%ort message* follo ed (y a mys,lP prompt t%at indicates t%e program is ready to accept ,ueries. o -o illustrate* %ere0s %at t%e elcome message loo+s li+e 1to save space* I on0t s%o it in any furt%er e'amples2: ; -)s;" 5elcome to t%e "yS[L monitor. $ommands end it% K or Zg.
38 Sree Sakthi Engineering College

8our "yS[L connection id is 69>7E to server version: =.7=.<6)log -ype 0%elpK0 or 0Z%0 for %elp. -ype 0Zc0 to clear t%e (uffer. mys,lP

o If mysql tries to start (ut e'its immediately it% an 3access denied3 message* you0ll need to specify connection parameters. o -%e most commonly needed parameters are t%e %ost to connect to 1t%e %ost %ere t%e "yS[L server runs2* your "yS[L username* and a pass ord. o /or e'ample: ; -)s;" 8h "oca"host 8p 8u cbuser @nter pass ord: cbpass

#.$.1.# Stoppin( 4)SN2 8ou can stop t%e "yS[L server (y e'ecuting t%is command: s%ellP OC@P!ro(ra- Fi"esP4)SN2P4)SN2 Ser%er ,.7PbinP-)s;"ad-inO 8u root shutdown #.$.1.$ 2o(out@ -o terminate a mysql session* issue a [UI- statement: mys,lP NUIT 8ou can also terminate t%e session (y issuing an @XI- statement or 1under Uni'2 (y typing $trl)&.

#.$.# Writin( )our Own SN2 pro(ra-s


5%en e'isting soft are doesn0t do %at you ant* you can rite your o n programs. 5e are going to create a simple login system using #J# code on our pages* and a "yS[L data(ase to store our userMs information. Sample $oding TAp%p
$host="localhost";

CC Jost name
39 Sree Sakthi Engineering College

CC "ys,l username $password=""; CC "ys,l pass ord $db_name="test"; CC &ata(ase name $tbl_name="members"; CC -a(le name
$username="";

CC $onnect to server and select data(se. mys,lYconnect13N%ost3* 3Nusername3* 3Npass ord32or die13cannot connect32K mys,lYselectYd(13Nd(Yname32or die13cannot select &?32K CC username and pass ord sent from form NmyusernameVNY#OS-Q0myusername0RK Nmypass ordVNY#OS-Q0mypass ord0RK Ns,lV3S@L@$- W /GO" Nt(lYname 5J@G@ usernameV0Nmyusername0 and pass ordV0Nmypass ord03K NresultVmys,lY,uery1Ns,l2K CC "ys,lYnumYro is counting ta(le ro NcountVmys,lYnumYro s1Nresult2K
// If result matched $myusername and $mypassword, table row must be 1 row

if1NcountVV62 ^

// Register $myusername, $mypassword and redirect to file "login_success php"

sessionYregister13myusername32K sessionYregister13mypass ord32K %eader13location:loginYsuccess.p%p32K ` else ^ ec%o 35rong Username or #ass ord3K ` AP

#.' Record se"ection Techno"o()


-%e S@L@$- statement is used to select data from a data(ase. -%e statement (egins it% t%e S@L@$- +ey ord. -%e (asic S@L@$- statement %as = clauses: o S@L@$o /GO"
40 Sree Sakthi Engineering College

o 5J@G@ -%e S@L@$- clause specifies t%e ta(le columns t%at are retrieved. -%e /GO" clause specifies t%e ta(les accessed. -%e 5J@G@ clause specifies 5J@G@ clause is optionalK if missing* all ta(le ro s are used. /or e'ample* S020CT na-e FRO4 e-p W>0R0 cit)Q+Ro-e+ -%is ,uery accesses ro s from t%e ta(le emp. It t%en filters t%ose ro s e'ample s ta(le* t%is ,uery produces: G8888888888888888888888G H name H G8888888888888888888888G H aravind%an H H anand+umar H G88888888888888888888888G S@L@$- gives you control over several aspects of record retrieval: o o o o o 5%ic% ta(le to use 5%ic% columns to display from t%e ta(le 5%at names to give t%e columns 5%ic% ro s to retrieve from t%e ta(le Jo to sort t%e ro s %ere t%e city column contains Gome. /inally* t%e ,uery retrieves t%e name column from eac% filtered ro . Using t%e %ic% ta(le ro s are used. -%e

$%ec+ing %at version of t%e server you0re running or t%e name of t%e current data(ase: mys,lP S020CT K0RSIONR D? D*T*5*S0R DJ
!-------------!------------! " #$%S&'(( ) " )*+*,*S$( )" !-------------!------------! " 3-23-.1-log " /oo01oo0 " !-------------!------------!

#.'.1 Specif)in( Which Co"u-ns to Disp"a) -o display some or all of t%e columns from a ta(le. Use W as a s%ortcut t%at selects all columns. Or name t%e columns you ant to see e'plicitly.
41 Sree Sakthi Engineering College

/or e'ample* mys,lP S020CT S FRO4 e-pJ


!---------------------!---------!---------! " name " age " e2 " !---------------------!---------!---------! " *nand3umar " 4. " 12 " !---------------------!---------!---------!

mys,lP S020CT na-e?a(e FRO4 e-pJ


!---------------------!---------! " name " age " !---------------------!---------! " *nand3umar " 4. " !---------------------!---------!

#.'.# .i%in( Na-es to Output Co"u-ns 5%enever you retrieve a result set* "yS[L gives every output column a name. 1-%at0s %o t%e mysql program gets t%e names t%at you see displayed as t%e initial ro of column %eaders in result set output.2 "yS[L assigns default names to output columns* (ut if t%e defaults are not suita(le* you can use column aliases to specify your o n names. mys,lP S020CT na-e?a(e FRO4 e-pJ
!---------------------!---------! " name " age " !---------------------!---------! " *nand3umar " 4. " !---------------------!---------!

mys,lP S020CT 0-p.Na-e as na-e? 0-p.*(e as a(e FRO4 e-pJ


!---------------------!---------! " $m -(ame " $m -*ge " !---------------------!---------! " *nand3umar " 4. " !---------------------!---------!

#.'.$ Specif)in( Which Rows to Se"ect Add a 5J@G@ clause to t%e ,uery t%at indicates to t%e server %ic% ro s to return. Unless you ,ualify or restrict a S@L@$- ,uery in some ay* it retrieves every ro in your ta(le* %ic% may (e a lot more information t%an you really ant to see.
42 Sree Sakthi Engineering College

mys,lP S020CT na-e?a(e FRO4 e-p W>0R0 na-eQTara%indTJ


!---------------------!---------! " name " age " !---------------------!---------! " aravind " 4. " !---------------------!---------!

#.'.' Re-o%in( Dup"icate Rows Use &IS-IN$- a ,uery eliminate duplicate values. Some ,ueries produce results containing duplicate records. /or e'ample* mys,lP S020CT na-e FRO4 e-pJ
!---------! " name " !---------! " aravind " " anand " " (aveen " " siva " " araivnd " " anand " !---------!

?ut t%at result is %eavily redundant. Adding &IS-IN$- to t%e ,uery removes t%e duplicate records* producing a set of uni,ue values: mys,lP S020CT na-e FRO4 e-pJ
!---------! " name " !---------! " aravind " " anand " " (aveen " " siva " !---------!

#.'., Wor&in( with NU22 Ka"ues -o summari.ing a set of values t%at may include NULL values and you need to +no %o to inter,ret the results. 7ost aggregate $un"tions ignore 8+LL #alues.

43 Sree Sakthi Engineering College

mys,lP S020CT subCect? test? score FRO4 e=pt ORD0R 59 subCect? testJ
!---------!------!-------! " su15e/t " test " s/ore " !---------!------!-------! " *run " * " 47 " " 6hitra " , " .0 " " )avid " 6 " (788 " " %am " ) " (788 " !---------!------!-------!

mys,lP S020CT subCect na-e FRO4 e=pt W>0R0 score IS NU22 .ROU! 59 subCectJ
!---------! " (ame " !---------! " )avid " " %am " !---------!

#.'./ Sortin( a Resu"t Set Add an OG&@G ?8 clause to tell it e'actly %o you ant t%ings sorted. 5%en you select ro s* t%e "yS[L server is free to return t%em in any order* unless you instruct it ot%er ise (y saying %o to sort t%e result. -%ere are lots of ays to use sorting tec%ni,ues. mys,lP S020CT na-e?a(e FRO4 e-p W>0R0 a(e U #' ORD0R 59 na-eJ
!---------!------! " name " age " !---------!------! " *run " 3. " " %am " 4. " " )avid " 34 " " 6hitra " .9 " !---------!------!

mys,lP S020CT na-e?a(e FRO4 e-p W>0R0 a(e U #' ORD0R 59 na-e *SCJ
!---------!------! " name " age " !---------!------! " *run " 3. " " 6hitra " 4. " " )avid " 34 "

44 Sree Sakthi Engineering College

" %am " .9 " !---------!------!

#., Wor&in( with Strin(s


A string can (e (inary or non(inary. ?inary strings are used for ra data suc% as images* music files* or encrypted values. Non(inary strings are used for c%aracter data suc% as te't and are associated it% a c%aracter set and collation 1sorting order2. A c%aracter set determines %ic% c%aracters are legal in a string. $ollations can (e c%osen according to %et%er you need comparisons to (e case)sensitive or case)insensitive* or to use t%e rules of a particular language. &ata types for (inary strings are BINARY* VARBINARY* and BLOB. &ata types for non(inary strings are CHAR* VARCHAR* and TEXT* eac% of columns. 8ou can convert a (inary string to a non(inary string and vice versa* or convert a non(inary string from one c%aracter set or collation to anot%er. 8ou can use a string in its entirety or e'tract su(strings from it. Strings can (e com(ined ot%er strings. 8ou can apply pattern)matc%ing operations to strings. FULLTEXT searc%ing is availa(le for efficient ,ueries on large collections of te't. #.,.1 Strin(s properties@ o Strings can (e case sensitive 1or not2* %ic% can affect t%e outcome of string operations. o 8ou can compare entire strings or 4ust parts of t%em (y e'tracting su(strings. o 8ou can apply pattern)matc%ing operations to loo+ for strings t%at %ave a certain structure. #.,.# T)pes of Strin(s it% %ic% allo s CHARACTER SET

and COLLATE attri(utes. See Gecipe <.7 for information a(out c%oosing data types for string

45 Sree Sakthi Engineering College

?inary data may contain (ytes t%at lie outside t%e usual range of printa(le AS$II c%aracters.A (inary string in "yS[L is one t%at "yS[L treats as case sensitive in comparisons./or (inary strings* t%e c%aracters A and a are considered different. /or non)(inary strings* t%ey0re considered t%e same. A (inary column type is one t%at contains (inary strings. Some of "yS[L0s column types are (inary 1case sensitive2 and ot%ers are not* as illustrated %ere: Co"u-n t)pe $JAG* ]AG$JAG $JAG ?INAG8* ]AG$JAG ?INAG8 -@X?LO? @NU"*S@No 8es No 8es No 5inar):case sensiti%e

A c%aracteristic of non(inary strings is t%at t%ey %ave a c%aracter set. -o see %ic% c%aracter sets are availa(le* use t%is statement: mys,lP S>OW C>*R*CT0R S0TJ Charset (ig< dec9 cp9<: %p9 +oi9r latin6 latin7 ... utf9 ucs7 Description ?ig< -raditional $%inese &@$ 5est @uropean &OS 5est @uropean J# 5est @uropean !OI9)G Gelcom Gussian cp67<7 5est @uropean ISO 99<D)7 $entral @uropean U-/)9 Unicode U$S)7 Unicode Defau"t co""ation (ig<Yc%ineseYci dec9Ys edis%Yci cp9<:YgeneralYci %p9Yenglis%Yci +oi9rYgeneralYci latin6Ys edis%Yci latin7YgeneralYci 7 6 6 6 6 6 6 4a="en

utf9YgeneralYci ucs7YgeneralYci

= 7
46

Sree Sakthi Engineering College

... -%e default c%aracter set in "yS[L is "atin1. -%e follo ing e'ample illustrates %o collation affects sort order. Suppose t%at a ta(le contains a latin6 string column and %as t%e follo ing ro s: mys,lP CR0*T0 T*520 t Rc C>*RR$D C>*R*CT0R S0T "atin1DJ mys,lP INS0RT INTO t RcD K*2U0SR+***+D?R+bbb+D?R+aaa+D?R+555+DJ mys,lP S020CT c FRO4 tJ
+------+ | C | +-------+ | AAA | | bbb | | aaa | | BBB | +-------+

#.,.$ Strin( Data T)pes@


o o o o o o o o o o o

$JAG ]AG$JAG -IN8-@X-@X?LO? "@&IU"-@XLONG-@X?INAG8 ]AG?INAG8 @NU" S@It is a fi'ed lengt% string and is mainly used %en t%e data is not going to vary muc% in

C>*RRD @ it0s lengt%. It ranges from : to 7<< c%aracters long. 5%ile storing $JAG values t%ey are rig%t
47 Sree Sakthi Engineering College

padded it% spaces to t%e specified lengt%. 5%en retrieving t%e $JAG values* trailing spaces are removed. K*RC>*RRD @ It is a varia(le lengt% string and is mainly used Note@ If $JAG and ]AG$JAG options are used in t%e same ta(le* t%en "yS[L allo s to enter a ma'imum num(er of c%aracters t%at TIN9T0AT? TIN952O5 @ A string it% a ma'imum lengt% of 7<< c%aracters. T0AT @ -@X- columns are treated as c%aracter strings1non)(inary strings2. It contains a ma'imum lengt% of B<<=< c%aracters. 52O5 @ ?LO? stands for ?inary Large O?4ect. It can %old a varia(le amount of data. ?LO? columns are treated as (yte strings1(inary strings2. It contains a ma'imum lengt% of B<<=< c%aracters. 40DIU4T0AT? 40DIU452O5 @ It %as a ma'imum lengt% of 6BEEE76< c%aracters. 2ON.T0AT? 2ON.52O5 @ It %as a ma'imum lengt% of >7D>DBE7D< c%aracters. 5IN*R9 @ -%e ?INAG8 is similar to t%e $JAG type. It stores t%e value as (inary (yte strings instead of non)(inary c%aracter strings. K*R5IN*R9 @
48 Sree Sakthi Engineering College

%en t%e data may vary in lengt%. It

ranges from : to 7<< c%aracters long. ]AG$JAG values are not padded %en t%ey are stored. ill

automatically c%ange t%e $JAG into ]AG$JAG for compata(ility reasons. -%e 1 2 (rac+et ill (e used in t%e column.

-%e ]AG?INAG8 is similar to t%e ]AG$JAG type. It stores t%e value as (inary (yte strings instead of non)(inary c%aracter strings. 0NU4RD @ An enumeration. @ac% column may %ave one of a specified possi(le values. It can store only one of t%e values t%at are declared in t%e specified list contained in t%e 1 2 (rac+ets. -%e @NU" list ranges up to B<<=< values. S0TRD @ A set. @ac% column may %ave more t%an one of t%e specified possi(le values. It contains up to B> list items and can store more t%an one c%oice. S@- values are represented internally as integers. #.,.' Choosin( a Strin( Data T)pe $%oose t%e data type according to t%e c%aracteristics of t%e information to (e stored and %o you need to use it. $onsider ,uestions suc% as t%ese:
o o o o o o

Are t%e strings (inary or non(inaryA &oes case sensitivity matterA 5%at is t%e ma'imum string lengt%A &o you ant to store fi'ed) or varia(le)lengt% valuesA &o you need to retain trailing spacesA Is t%ere a fi'ed set of allo a(le valuesA

"yS[L provides several (inary and non(inary string data types. -%ese types come in pairs as s%o n in t%e follo ing ta(le. 5inar) data t)pe ?INAG8 ]AG?INAG8 Nonbinar) data t)pe $JAG ]AG$JAG 4a=i-u- "en(th 7<< B<*<=<
49 Sree Sakthi Engineering College

-IN8?LO? ?LO? "@&IU"?LO? LONG?LO?

-IN8-@X-@X"@&IU"-@XLONG-@X-

7<< B<*<=< 6B*EEE*76< >*7D>*DBE*7D<

#./ Date and Ti-e Data T)pes


"yS[L supports a num(er of date and time column formats. /or all t%e date and time columns* e can also assign t%e values using eit%er string or num(ers. o &A-@ o -I"@ o &A-@-I"@ o -I"@S-A"# o 8@AG D*T0@ A &ate. -%e range is 6:::):6):6 to DDDD)67)=6. -%e date values are displayed in 8888)"") && format. TI40@ A -ime. -%e range is )9=9:<D:<D to 9=9:<D:<D. -%e time values are displayed in JJ:"":SS format. D*T0TI40@ A &ate and -ime com(ination. -%e range is 6:::):6):6 :::::::: to DDDD)67)=6 7=:<D:<D. -%e date time values are displayed in 8888)"")&& JJ:"":SS format. TI40ST*4!@ A -imestamp. -%e range is 6DE:):6):6 :::::::6 U-$ to part ay t%roug% t%e year 7:=E. A -I"@S-A"# column is useful for recording t%e date and time of an INS@G- or U#&A-@ operation. 90*R@
50 Sree Sakthi Engineering College

A 8ear. -%e year values are displayed eit%er in t o)digit or four)digit format. -%e range of values for a four)digit is 6D:6 to 76<<. /or t o)digit* t%e range is E: to BD* representing years from 6DE: to 7:BD. /or @'ample mys,lP S020CT t1? t# FRO4 ti-eE%a"J
!----------!----------! " t1 " t2 " !----------!----------! " 1.:00:00 " 1.:00:00 " " 0.:01:30 " 02:30:20 " " 12:30:20 " 17:30:4. " !----------!----------!

mys,lP S020CT d FRO4 dateE%a"J


!------------! " d " !------------! " 1:94-02-2: " " 1;00-01-1. " " 1;:7-03-0. " " 1;;;-12-31 " " 2000-09-04 " !------------!

#./.1 Date and Ti-e For-ats 5%ilst it is most common to store dates using a das% 1)2 as t%e delimiter and a colon 1:2 as t%e time delimiter it is in fact possi(le to use any c%aracter* or no c%aracter (et een t%e date and time segments. /or e'ample* t%e follo ing formats all ac%ieve t%e same result: 7::9)6:)7= 6::=E:77 7::96:7=6:=E77 7::9C6:C7= 6:.=E.77 7::9W6:W7=W6:W=EW77

51 Sree Sakthi Engineering College

#./.# Date and Ti-e Functions In addition to providing mec%anisms for storing dates and times* "yS[L also provides a ide range of functions t%at can (e used to manipulate dates and times. -%e follo ing ta(le provides a list of t%e more common functions availa(le for "yS[L: Function A&&&A-@12 A&&-I"@12 $ON]@G-Y-\12 $UG&A-@12 $UG-I"@12 &A-@YA&&12 &A-@Y/OG"A-12 &A-@YSU?12 &A-@12 &A-@&I//12 &A8NA"@12 &A8O/"ON-J12 &A8O/5@@!12 &A8O/8@AG12 @X-GA$/GO"Y&A8S12 /GO"YUNIX-I"@12 G@-Y/OG"A-12 JOUG12 LAS-Y&A8 "A!@&A-@12 "A!@-I"@ "I$GOS@$ON&12 "INU-@12 "ON-J12 "ON-JNA"@12 Description Add dates Add time $onvert from one time.one to anot%er Geturns t%e current date Geturns t%e current system time Add t o dates /ormat date as specified Su(tract t o dates @'tract t%e date part of a date or datetime e'pression Su(tract t o dates Geturns t%e name of t%e ee+day Geturns t%e day of t%e mont% 16)=62 Geturns t%e ee+day inde' of t%e argument Geturns t%e day of t%e year 16)=BB2 @'tract part of a date $onvert a day num(er to a date /ormat date as a UNIX timestamp Geturns a date format string @'tract t%e %our Geturns t%e last day of t%e mont% for t%e argument $reate a date from t%e year and day of year "A!@-I"@12 Geturns t%e microseconds from argument Geturns t%e minute from t%e argument Geturns t%e mont% from t%e date passed Geturns t%e name of t%e mont%
52 Sree Sakthi Engineering College

or+ing

it% times and dates in

NO512 #@GIO&YA&&12 #@GIO&Y&I//12 [UAG-@G12 S@$Y-OY-I"@12 S@$ON&12 S-GY-OY&A-@12 SU?-I"@12 S8S&A-@12 -I"@Y/OG"A-12 -I"@Y-OYS@$12 -I"@12 -I"@&I//12 -I"@S-A"#12

Geturns t%e current date and time Add a period to a year)mont% Geturns t%e num(er of mont%s (et een t o periods Geturns t%e ,uarter from a date passed as an argument $onverts seconds to 0JJ:"":SS0 format Geturns t%e second 1:)<D2 $onvert a string to a date Su(tract times Geturns t%e time at %ic% t%e function e'ecutes /ormat as time Geturns t%e argument converted to seconds @'tract t%e time portion of t%e e'pression passed as an argument Su(tract time 5it% a single argument* t%is function returns t%e &ate or t%e &atetime

e'pression. 5it% t o arguments* t%e sum of t%e arguments is returned -I"@S-A"#A&&12 Add an interval to a datetime e'pression -I"@S-A"#&I//12 Su(tract an interval from a datetime e'pression -OY&A8S12 Geturns t%e date argument converted to days UNIXY-I"@S-A"#12 Geturns a UNIX timestamp to a format accepta(le to "yS[L U-$Y&A-@12 Geturns t%e current Universal -ime 1U-$2 date U-$Y-I"@12 Geturns t%e current Universal -ime 1U-$ time U-$Y-I"@S-A"#12 Geturns t%e current Universal -ime 1U-$2 date and time 5@@!12 Geturns t%e ee+ num(er 5@@!&A812 Geturns t%e ee+day inde' 5@@!O/8@AG12 Geturns t%e calendar ee+ of t%e date 16)<=2 8@AG12 Geturns t%e year 8@AG5@@!12 Geturns t%e year and ee+

#./.$ Disp"a) Dates or Ti-es Use t%e &A-@Y/OG"A-1 2 or -I"@Y/OG"A-1 2 functions to re rite t%e &A-@Y/OG"A-1 2 function* %ic% ta+es t o arguments: a &A-@* &A-@-I"@* or -I"@S-A"# value* and a string descri(ing %o to display t%e value.
53 Sree Sakthi Engineering College

5it%in t%e formatting string* you indicate %at to display using special se,uences of t%e form ;c* %ere c specifies %ic% part of t%e date to display. /or e'ample* ;8* ;"* and ;d signify t%e four)digit year* t%e mont% name* and t%e t o)digit day of t%e mont%. -%e follo ing ,uery s%o s t%e values in t%e dateYval ta(le* (ot% as "yS[L displays t%em (y default and as reformatted it% &A-@Y/OG"A-1 2: mys,lP S020CT d? D*T0EFOR4*TRd?+V4 Vd? V9+D FRO4 dateE%a"J
!------------!----------------------------! " d " )*+$<='%>*+(d?@A> Ad? AB@) " !------------!----------------------------! " 1:94-02-2: " =e1ruarC 2:? 1:94 " " 1;00-01-1. " DanuarC 1.? 1;00 " " 1;:7-03-0. " >ar/h 0.? 1;:7 " " 1;;;-12-31 " )e/em1er 31? 1;;; " " 2000-09-04 " Dune 04? 2000 " !------------!----------------------------!

#.1 Sortin( Nuer) Resu"ts. S[L S020CT command to fetc% data from "yS[L ta(le. 5%en you select ro s* t%e "yS[L server is free to return t%em in any order* unless you instruct it ot%er ise (y saying %o to sort t%e result. ?ut a ,uery doesn0t come out in t%e order you ant. #.1.1 Usin( ORD0R 59 to Sort Nuer) Resu"ts Add an OG&@G ?8 clause. OG&@G ?8 ill tell t%e "yS[L server to sort t%e ro s (y a column. &efine in %ic% direction to sort* as t%e order of t%e returned ro s may not yet (e meaningful. Go s can (e returned in ascending or descending order. Use AS$ or &@S$. Using AS$ ill sort t%e data so t%at you see t%e smallest num(er first. Using &@S$ ill sort t%e data so t%at you see t%e largest num(er first. In t%is ,uery* you are loo+ing for customers it% t%e largest negative (alance first. OG&@G ?8 ill return t%e arrays it% t%e greatest negative num(er 1t%e smallest num(er2 at t%e top. S)nta=@

54 Sree Sakthi Engineering College

Jere is generic S[L synta' of S@L@$- command along it% OG&@G ?8 clause to sort data from "yS[L ta(le: S@L@$- field6* field7*...fieldN ta(leYname6* ta(leYname7... OG&@G ?8 field6* Qfield7...R QAS$ Q&@S$RR o 8ou can sort returned result on any field provided t%at filed is (eing listed out.
o o

8ou can sort result on more t%an one field. 8ou can use +ey ord AS$ or &@S$ to get result in ascending or descending order. ?y default its ascending order. 8ou can use 5J@G@...LI!@ clause in usual ay to put condition.

0=a-p"e@
mCsEl> S$8$6+ F Grom tutorials<t1l '%)$% ,B tutorial<author *S6 !-------------!----------------!-----------------!-----------------! " tutorial<id " tutorial<title " tutorial<author " su1mission<date " !-------------!----------------!-----------------!-----------------! " 2 " 8earn >CSH8 " *1dul S " 2007-0.-24 " " 1 " 8earn IJI " Dohn Ioul " 2007-0.-24 " " 3 " D*#* +utorial " San5aC " 2007-0.-09 " !-------------!----------------!-----------------!-----------------!

#.1.# Sortin( Subsets of a Tab"e 8ou don0t ant to sort an entire ta(le* 4ust part of it. Add a 5J@G@ clause t%at selects many ro s t%ere areK it sorts %atever ro s t%e ,uery %ic% ro s to only t%e records you ant to see. OG&@G ?8 doesn0t care %o returns. If you don0t ant to sort an entire ta(le* add a 5J@G@ clause to indicate

select. /or e'ample* to sort t%e records for 4ust one of t%e drivers* do somet%ing li+e t%is: mys,lP S020CT tra%Edate? -i"es FRO4 dri%erE"o( W>0R0 na-e Q +>enr)+ ORD0R 59 tra%EdateJ
!------------!-------! " trav<date " miles " !------------!-------! " 2001-11-29 " 11. " " 2001-11-27 " ;9 "

55 Sree Sakthi Engineering College

" 2001-11-2; " 300 " " 2001-11-30 " 203 " " 2001-12-01 " 1;7 " !------------!-------!

#.1.$ Disp"a)in( One Set of Ka"ues Whi"e Sortin( b) *nother -o sort a result set using values t%at you0re not selecting. 8ou can use columns in t%e OG&@G ?8 clause t%at doesnMt appear in t%e column output list. OG&@G ?8 is not limited to sorting only t%ose columns named in t%e column output list. It can sort using values t%at are 3%idden3. #.1.' Sortin( and NU22 Ka"ues -o sort columns t%at may contain NULL values. If NULL values don0t come out in t%e desired position it%in t%e sort order* /alse t%em into appearing %ere you ant. 5%en a sorted column contains NULL values* "yS[L puts t%em all toget%er in t%e sort order. mys,lP S020CT NU22 Q NU22J
!-------------! " (788 = (788 " !-------------! " (788 " !-------------!

Normally* sorting puts t%e NULL values at t%e (eginning: mys,lP S020CT %a" FRO4 t ORD0R 59 %a"J
!------! " val " !------! " (788 " " (788 " " 3 " " ; " " 100 " !------!

#.1., Date85ased Sortin(

56 Sree Sakthi Engineering College

-o sort in temporal order. Sort using a date or time column type* ignoring parts of t%e values t%at are irrelevant if necessary. "any types of information include date or time information and it0s very often necessary to sort results in temporal order. "yS[L +no s %o to sort temporal column types* so t%ere0s no special tric+ to ordering values in &A-@* &A-@-I"@* -I"@* or -I"@S-A"# columns. ?egin it% a ta(le t%at contains values for eac% of t%ose types: mys,lP S020CT S FRO4 te-pora"E%a"J
!------------!---------------------!----------!----------------! " d " dt " t " ts " !------------!---------------------!----------!----------------! " 1;70-01-01 " 1::4-01-01 12:00:00 " 13:00:00 " 1;:00101020000 " " 1;;;-01-01 " 1:90-01-01 12:00:00 " 1;:00:00 " 20210101030000 " " 1;:1-01-01 " 1:71-01-01 12:00:00 " 03:00:00 " 1;7.0101040000 " " 1;94-01-01 " 1:;;-01-01 12:00:00 " 01:00:00 " 1;:.01010.0000 " !------------!---------------------!----------!----------------!

#.1./ Sortin( b) Ca"endar Da)

-o sort (y day of t%e calendar year. Sort using t%e mont% and day of a date* ignoring t%e year. Sorting in calendar order differs from sorting (y date. 8ou ignore t%e year part of t%e dates and sort using only t%e mont% and day to order records in terms of %ere t%ey fall during t%e calendar year. Suppose you %ave an event ta(le t%at loo+s li+e t%is %en values are ordered (y actual date of occurrence: mys,lP S020CT date? description FRO4 e%ent ORD0R 59 dateJ
!------------!-------------------------------------! " date " des/ri tion " !------------!-------------------------------------! " 121.-09-1. " Signing oG the >agna 6arta " " 1732-02-22 " Keorge Lashington@s 1irthdaC " " 1779-07-14 " ,astille )aC " " 17:;-07-04 " 7S &nde enden/e )aC " " 1;:;-11-0; " ' ening oG the ,erlin Lall " !------------!-------------------------------------!

#.3 .eneratin( Su--ar)


Summaries are useful Summary tec%ni,ues allo %en you ant t%e overall picture rat%er t%an t%e details. Once t%e ill (e displayed.
57 Sree Sakthi Engineering College

(ul+ 1unpac+ed2 data transfer is complete* a summary report of t%e migration you to ans er ,uestions suc% as 3Jo

manyA3 or 35%at is t%e

totalA3 or 35%at is t%e range of valuesAF Summary operations in "yS[L involve t%e follo ing S[L constructs: Using aggregate function e can ac%ieve summary of values. Aggregate functions are $OUN- 12* "IN 12* "AX 12* SU". 12* A]G 12 and GGOU# ?8 clause to group t%e ro s into su(sets and o(tain an aggregate value for eac% one. -o getting a list of uni,ue values* use S@L@$- &IS-IN$- rat%er t%an S@L@$-. Using $OUN- 1&IS-IN$-2 ) -o count %o distinct values t%ere are. #.3.1 Su--ari<in( with COUNTR D -o count t%e num(er of ro s in an entire ta(le or t%at matc% particular conditions* use t%e $OUN-1 2 function. /or e'ample* mys,lP S020CT COUNTRSD FRO4 e-pEtabJ
!----------! " 6'7(+(F) " !----------! " 30 " !----------!

many

#.3.# Su--ari<in( with 4INR D and 4*AR D /inding smallest or largest values in an entire ta(le* use t%e "IN 12 and "AX 12 function. /or e'ample* mys,lP S020CT 4INRSa"D *S "ow? 4*ARsa"D *S hi(h FRO4 e-pEtabJ
!--------------! " 8ow " Jigh " !--------------! " 100 " .00 " !--------------!

#.3.$ Su--ari<in( with SU4R D and *K.R D SU"1 2 and A]G1 2 produce t%e total and average 1mean2 of a set of values: /or @'ample*
58 Sree Sakthi Engineering College

mys,lP S020CT SU4RrnoD *S +No8Of 0-p+? *K.Rsa"D *S +*%( Sa"+ FRO4 e-pEtabJ
!--------------<------! " (o-'G $m " *vg Sal " !---------------<-----! " 234.9 " :.00 " !----------------------!

#.3.' Usin( DISTINCT to 0"i-inate Dup"icates A summary operation t%at doesn0t use aggregate functions is to determine %ic% values or ro s are contained in a dataset (y eliminating duplicates. &o t%is it% &IS-IN$-. &IS-IN$- is useful for (oiling do n a ,uery result* and often is com(ined listed in t%e empYta( ta(le* use t%e follo ing ,uery: mys,lP S020CT DISTINCT e-pEna-e FRO4 e-pEtab ORD0R 59 e-pEna-eJ
!-------! " name " !-------! " *run " " Dohn " " %am " !-------!

it% OG&@G ?8 to place t%e

values in more meaningful order. /or e'ample* if you ant to +no t%e names of t%e employees

A ,uery it%out &IS-IN$- produces t%e same names* (ut is not nearly as easy to understand: mys,lP S020CT e-pEna-e FRO4 e-pEtabJ
!-------! " name " !-------! " *run " " Dhon " " %am " " %am " " *run " " *run " !-------!

59 Sree Sakthi Engineering College

If you ant to +no %o many different drivers t%ere are* use $OUN-1&IS-IN$-2: mys,lP S020CT COUNTRDISTINCT e-pEna-eD FRO4 e-pEtabJ
!----------------------! " 6'7(+()&S+&(6+ em <name) " !----------------------! " 3 " !----------------------!

#.3., Di%idin( a Su--ar) into Sub(roups -o calculate a summary for eac% su(group of a set of ro s* not an overall summary ]alue use a GGOU# ?8 clause to arrange ro s into groups. 5it%out using GGOU# ?8 mys,lP S020CT COUNTRSD FRO4 dri%erE"o(J
!----------! " 6'7(+(F) " !----------! " 10 " !----------!

Using GGOU# ?8 mys,lP S020CT na-e? COUNTRna-eD FRO4 dri%erE"o( .ROU! 59 na-eJ
!-------!-------------! " name " 6'7(+(name) " !-------!-------------! " ,en " 3 " " JenrC " . " " SuMi " 2 " !-------!-------------!

#.3./ Su--aries and NU22 Ka"ues -o summari.ing a set of values t%at may include NULL values and you need to +no %o to interpret t%e results. "ost aggregate functions ignore NULL values.

60 Sree Sakthi Engineering College

mys,lP S020CT subCect? test? score FRO4 e=pt ORD0R 59 subCect? testJ
!---------!------!-------! " su15e/t " test " s/ore " !---------!------!-------! " *run " * " 47 " " 6hitra " , " .0 " " )avid " 6 " (788 " " %am " ) " (788 " !---------!------!-------!

mys,lP S020CT subCect na-e FRO4 e=pt W>0R0 score IS NU22 .ROU! 59 subCectJ
!---------! " (ame " !---------! " )avid " " %am " !---------!

#.3.1 Deter-inin( Whether Ka"ues are Uni;ue

-o +no

%et%er ta(le values are uni,ue use JA]ING in con4unction it% $OUN-1 2.

mys,lP S020CT tra%Edate? COUNTRtra%EdateD FRO4 dri%erE"o( .ROU! 59 tra%Edate >*KIN. COUNTRtra%EdateD Q 1J
!------------!------------------! " trav<date " 6'7(+(trav<date) " !------------!------------------! " 2001-11-29 " 1 " " 2001-11-27 " 1 " " 2001-12-01 " 1 " !------------!------------------!

#.6 Wor&in( with 4etadata


"etadata is data a(out data. /or e'ample ) $onsider a file it% a picture. -%e picture or t%e pi'els inside t%e file are data. A description of t%e picture* li+e 3L#@G format* =::'>:: pi'els* E7dpi3* is metadata* (ecause it descri(es t%e content of t%e file* alt%oug% it0s not t%e actual data.

#.6.1 Representation of -etadata -ust satisf) these re;uire-ents@


61 Sree Sakthi Engineering College

All metadata must (e in t%e same c%aracter set. Ot%er ise* neit%er t%e SJO5 statements nor S@L@$- statements for ta(les in IN/OG"A-IONYS$J@"A c%aracter sets. "etadata must include all c%aracters in all languages. Ot%er ise* users name columns and ta(les using t%eir o n languages. ould not (e a(le to ould or+ properly (ecause ould (e in different different ro s in t%e same column of t%e results of t%ese operations

#.6.# T)pes of 4etadata


Information a(out t%e result of ,ueries 5%en you delete or update a set of ro s* you can determine t%e num(er of ro s t%at ere c%anged. Information a(out ta(les and data(ases. Information affecting to t%e structure of ta(les and data(ases is useful for applications t%at need to count a list of ta(les in a data(ase or data(ases %osted on a server. Information a(out t%e "yS[L server. Some A#Is provide information a(out t%e data(ase server or a(out t%e status of your current connection it% t%e server.

#.6.$ Obtainin( Resu"t Set 4etadata


/or ,ueries t%at generate a result set* you can get a num(er of +inds of metadata. !>!@ In #J#* metadata information is availa(le after a successful call to mys,lY,uery1 2 and remains accessi(le up to t%e point at %ic% you call mys,lYfreeYresult1 2. -o access t%e metadata* pass t%e result set identifier returned (y mys,lY,uery1 2 to t%e function t%at returns t%e information you ant. -o get a ro single o(4ect. or column count for a result set* invo+e mys,lYnumYro s1 2 or mys,lYnumYfields1 2. "etadata information for a given column in a result set is pac+aged up in a

62 Sree Sakthi Engineering College

#.17 Usin( Se;uences


A se,uence is a data(ase o(4ect t%at generates num(ers in se,uential order. Applications most often use t%ese num(ers %en t%ey re,uire a uni,ue value in a ta(le suc% as primary +ey values. -%e follo ing list descri(es t%e c%aracteristics of se,uences.
o o o

Se,uences are availa(le to all users of t%e data(ase Se,uences are created using S[L statements 1see (elo 2 Se,uences %ave a minimum and ma'imum value 1t%e defaults are minimumV: and ma'imumV7B=)62K t%ey can (e dropped* (ut not reset

o o

Once a se,uence returns a value* t%e se,uence can never return t%at same value 5%ile se,uence values are not tied to any particular ta(le* a se,uence is usually used to generate values for only one ta(le

Se,uences increment (y an amount specified %en created 1t%e default is 62

#.17.1Creatin( a Se;uence -o create se,uences* e'ecute a $G@A-@ S@[U@N$@ statement in t%e same -%e format for a $G@A-@ S@[U@N$@ statement is as follo s: $G@A-@ S@[U@N$@ se,uenceYname QIN$G@"@N- ?8 SR QS-AG- 5I-J SR Q"AX]ALU@ S _ NO"AX]ALU@R Q"IN]ALU@ S _ NO"IN]ALU@R Q$8$L@ _ NO$8$L@R Kariab"e Description IN$G@"@N- ?8 -%e increment value. -%is can (e a positive or negative num(er. S-AG- 5I-J -%e start value for t%e se,uence. "AX]ALU@ -%e ma'imum value t%at t%e se,uence can generate. If specifying
63 Sree Sakthi Engineering College

ay as an

U#&A-@ or INS@G- statement. -%e se,uence information is stored in a data dictionary file.

"IN]ALU@ $8$L@

NO"AX]ALU@* t%e ma'imum value is 7B=)6. -%e minimum value t%at t%e se,uence can generate. If specifying NO"IN]ALU@* t%e minimum value is )7B=. Specify $8$L@ to indicate t%at %en t%e ma'imum value is reac%ed t%e se,uence starts over again at t%e start value. Specify NO$8$L@ to generate an error upon reac%ing t%e ma'imum value.

#.17.# Droppin( a Se;uence -o drop a se,uence* e'ecute a &GO# S@[U@N$@ statement. Use t%is function drop t%e se,uence and t%en recreate it.&rop a se,uence follo ing t%is format: DRO! S0NU0NC0 -)Ese;uence #.17.$ Usin( a Se;uence Use se,uences %en an application re,uires a uni,ue identifier. INS@G- statements* and occasionally U#&A-@ statements* are t%e most common places to use se,uences. - o 3functions3 are availa(le on se,uences: N0ATK*2@ Geturns t%e ne't value from t%e se,uence. CURK*2@ Geturns t%e value from t%e last call to N@X-]AL (y t%e current user during t%e current connection. /or e'ample* if User A calls N@X-]AL and it returns 67>* and User ? immediately calls N@X-]AL getting 67<* User A ill get 67> %en calling $UG]AL* %ile User ? ill get 67< %ile calling $UG]AL. It is important to understand t%e connection (et een t%e se,uence value and a particular connection to t%e data(ase. -%e user cannot call $UG]AL until ma+ing a call to N@X-]AL at least once on t%e connection. $UG]AL returns t%e current value returned from t%e se,uence on t%e current connection* not t%e current value of t%e se,uence. 0=a-p"es -o create t%e se,uence: $G@A-@ S@[U@N$@ customerYse, IN$G@"@N- ?8 6 S-AG- 5I-J 6::
64 Sree Sakthi Engineering College

%en a

se,uence is no longer useful* or to reset a se,uence to an older num(er. -o reset a se,uence* first

-o use t%e se,uence to enter a record into t%e data(ase: INS@G- IN-O customer 1custYnum* name* address2 ]ALU@S customerYse,.N@X-]AL* 0!alam0* 067= Gand%i Nagar.02 -o find t%e value 4ust entered into t%e data(ase: S@L@$- customerYse,.$UG]AL AS LAS-Y$US-YNU

#.11 4)SN2 and Web


o "yS[L ma+es it easier to provide dynamic rat%er t%an static content. Static content e'ists as pages in t%e e( server0s document t%at are served e'actly as is. o ]isitors can access only t%e documents t%at you place in t%e tree* and c%anges occur only %en you add* modify* or delete t%ose documents. o ?y contrast* dynamic content is created on demand. #.11.1 5asic Web !a(e .eneration Using J-"L e can generate your o n 5e( site. J-"L is a language for descri(ing e( pages.
o o o o o o o

J-"L stands for >yper Te't 4ar+up 2anguage J-"L is not a programming language* it is a -ar&up "an(ua(e A mar+up language is a set of -ar&up ta(s J-"L uses -ar&up ta(s to descri(e e( pages J-"L documents describe web pa(es J-"L documents contain >T42 ta(s and plain te't J-"L documents are also ca""ed web pa(es.

65 Sree Sakthi Engineering College

Jere is a very simple J-"L page t%at specifies a title in t%e page %eader* and a (ody it% %ite (ac+ground containing a single paragrap%: TJtmlP T?odyP TJ6P"y JeadingTCJ6P 5elcome -o "y 5e( #age T#P"y #aragrap%TC#P T(ody (gcolorV3green3P TC?odyP TCJtmlP Static Web !a(e: A static e( page s%o s t%e re,uired information to t%e vie er* (ut do not e( page displays t%e information to t%e vie er and also accept any information from t%e vie er. D)na-ic Web !a(e: A dynamic dynamic e( page. C"ient side scriptin( is a script* 1e'. Lavascript* ]? script2* t%at is e'ecuted (y t%e (ro ser 1i.e. /irefo'* Internet @'plorer* Safari* Opera* etc.2 t%at resides at t%e user computer. Ser%er side scriptin(* 1e'. AS#.Net* AS#* LS#* #J#* Gu(y* or ot%ers2* is e'ecuted (y t%e server 15e( Server2* and t%e page t%at is sent to t%e (ro ser is produced (y t%e serve)side scripting. #.11.# Usin( *pache to Run Web Scripts o Open)Source 5e( server originally (ased on N$SA server1National $enter for Supercomputing Applications2. o Apac%e is t%e most idely used e( server soft are pac+age in t%e orld. o Apac%e is %ig%ly configura(le and can (e setup to support tec%nologies suc% as* pass ord protection* virtual %osting 1name (ased and I# (ased2* and SSL encryption. -%ere are typically several directories under t%e Apac%e root directory* (e CusrClocalCapac%e. -%ese directories include:
66 Sree Sakthi Engineering College

accepts t%e information from t%e user Gail ay reservation* Online s%opping etc. are e'amples of

%ic% I0ll assume %ereto

(in : $ontains %ttpdat%at is* Apac%e itselfaand ot%er Apac%e)related e'ecuta(le programs. conf : /or configuration files* nota(ly %ttpd.conf* t%e primary file used (y Apac%e. Jtdocs : -%e root of t%e document tree Logs : /or log files -o configure Apac%e for script e'ecution* edit t%e httpd.conf file in t%e conf directory.

UNIT III

OPEN SOURCE PROGRAMMING LANGUAGES

9:9/ ;ntro'u"tion < 9rogra!!ing in *e& en#iron!ent < #aria&les < "onstants < =ata t ,es < o,erators < State!ents < >un"tions < Arra s < 669 < String 7ani,ulation an' regular ex,ression < >ile han'ling an' 'ata storage < 9:9 an' S?L 'ata&ase < 9:9 an' L=A9 < 9:9 Conne"ti#it < Sen'ing an' re"ei#ing E@!ails < =e&ugging an' error han'ling < Se"urit < .e!,lates.

67 Sree Sakthi Engineering College

3 ! P"P: Intro#$ction% Progra&&ing in 'e( en)iron&ent 9:9 &ro*ser% so is a ser#er@si'e s"ri,ting language. 9:9 stan's $or : ,ertext

9re,ro"essor. .his !eans that the s"ri,t is run on our *e& ser#er% not on the user-s ou 'o not nee' to *orr a&out "o!,ati&ilit issues. 9:9 is relati#el &e"o!ing ne* 1"o!,are' to languages su"h as 9erl 1CA;2 an' Ba#a2 &ut is 4ui"kl

one o$ the !ost ,o,ular s"ri,ting languages on the internet. 9:9 su,,orts !an 'ata&ases 17 S?L% ;n$or!ix% 6ra"le% S &ase% Soli'% 9ostgreS?L% Aeneri" 6=CC% et".2 9:9 is an o,en sour"e so$t*are 9:9 is $ree to 'o*nloa' an' use. 9:9 $iles "an "ontain text% :.7L tags an' s"ri,ts.9:9 $iles are returne' to the &ro*ser as ,lain :.7L.9:9 $iles ha#e a $ile extension o$ 5.,h,5% 5.,h,35% or 5.,ht!l5. 9:9 ena&les ou to &uil' large% "o!,lex% an' ' na!i" *e&sites. 9:9 "an also in"rease our ,ro'u"ti#it enor!ousl % &oth in 'e#elo,!ent ti!e an' !aintenan"e ti!e. +sing 9:9% ou "an &uil' *e&sites that 'o things su"h as/ o o o o o o o ?uer a 'ata&ase Allo* users to u,loa' $iles CreateDrea' $iles on the ser#er 1$or exa!,le% the $iles that our users u,loa'2 :a#e a 5!e!&er-s area5 1i.e. #ia a login ,age2 :a#e a sho,,ing "art 9resent a "usto!iEe' ex,erien"e 1$or exa!,le% &ase' on users- &ro*sing histor 2 7u"h% !u"h !ore

3 ! ! Creating a P"P *ile .o "reate a 9:9 $ile% si!,l 'o the $ollo*ing/ Create a ne* $ile in our $a#orite e'itor 68 Sree Sakthi Engineering College

. ,e so!e 9:9 "o'e Sa#e the $ile *ith a .,h, extension .he .,h, extension tells the *e& ser#er that it nee's to ,ro"ess this as a 9:9 $ile. ;$ ou a""i'entall sa#e it *ith a .ht!l extension the ser#er *on-t ,ro"ess our 9:9 "o'e an' the &ro*ser *ill )ust out,ut it all to the s"reen. 3 ! + Si&ple E,a&ple: E#er &lo"k o$ 9:9 "o'e !ust start *ith FG,h, an' en' *ith GH. .he

$ollo*ing exa!,le out,uts the text 59:9 is eas I5 to the s"reen/ Fht!lH Fhea'H FtitleH9:9 S ntax Exa!,leFDtitleH FDhea'H F&o' H FG,h, e"ho 59:9 is eas I5J GH FD&o' H FDht!lH 3 ! 3 Co&&ents (hile there is onl one t ,e o$ "o!!ent in :.7L% 9:9 has t*o t ,es. .he

$irst t ,e *e *ill 'is"uss is the single line "o!!ent. .he single line "o!!ent tells the inter,reter to ignore e#er thing that o""urs on that line to the right o$ the

69 Sree Sakthi Engineering College

"o!!ent. .o 'o a single line "o!!ent t ,e 5DD5 or 5K5 an' all text to the right *ill &e ignore' & 9:9 inter,reter. Exa!,le/ Fht!lH F&o' H FG,h, DD.his is a "o!!ent DL.his isa "o!!ent &lo"k LD GH FD&o' H FDht!lH

3 + -aria(les 3 + ! Intro#$ction Maria&les are na!e' 5"ontainers5 that allo* ou to store a #alue or Maria&les are nothing &ut i'enti$iers to the !e!or lo"ation to store 'ata. .his #alue "an then &e use' & other ,arts o$ the a,,li"ation% si!,l & re$erring to the #aria&le-s na!e. >or exa!,le% the a,,li"ation "oul' 'is,la the "ontents o$ the #aria&le to the user. ;n 9:9% #aria&le na!es !ust start *ith a 'ollar sign 1N2. >or exa!,le/ FG,h, 70 Sree Sakthi Engineering College

N! Maria&le O 59:9 is eas I5J e"ho N! Maria&leJ GH 3 + + -aria(le Na&es (hen "reating na!es $or *ith the $ollo*ing na!ing rules/ o o o All 9:9 #aria&le na!es !ust start *ith a letter or un'ers"ore 1 P 25 Maria&le na!es "an onl "ontain al,ha@nu!eri" "hara"ters an' un'ers"ores 1 i.e. a@E% A@Q% 0@9% or P 2 Maria&le na!es !ust not "ontain s,a"es. >or !ulti@*or' #aria&le na!es% either se,arate the *or's *ith an un'ers"ore 1 P 2 or use "a,italiEation. 3 + 3 P"P is a Loosel. T.pe# Lang$age 9:9 is a loosel t ,e language% *hi"h !eans that ou 'o not nee' to 'e"lare a #aria&le &e$ore assigning a #alue to it .;n 9:9% the #aria&le is 'e"lare' auto!ati"all *hen ou use it. >or Exa!,le% FG,h, NtxtO5:ello (orl'I5J NxO16J GH 3 + / String -aria(les in P"P A string #aria&le is use' to store an' !ani,ulate text. String #aria&les are use' $or #alues that "ontains "hara"ters. >or Exa!,le% FG,h, 71 Sree Sakthi Engineering College our #aria&les% ou nee' to ensure the "o!,l

NtxtO5:ello (orl'5J e"ho NtxtJ GH 3 + 0 T1e Concatenation Operator .here is onl one string o,erator in 9:9..he "on"atenation o,erator 1.2 is use' to

,ut t*o string #alues together..o "on"atenate t*o string #aria&les together% use the "on"atenation o,erator/ FG,h, Ntxt1O5:ello (orl'I5J Ntxt2O5(hat a ni"e 'a I5J e"ho Ntxt1 . 5 5 . Ntxt2J GH 6ut,ut/ :ello (orl'I (hat a ni"e 'a I T1e strlen23 4$nction .he strlen12 $un"tion is use' to return the length o$ a string. FG,h, e"ho strlen15:ello *orl'I52J GH 6ut,ut/ 12 T1e strpos23 4$nction .he str,os12 $un"tion is use' to sear"h $or "hara"ter *ithin a string. 72 Sree Sakthi Engineering College

FG,h, e"ho str,os15:ello *orl'I5%5*orl'52J GH 6ut,ut/ 6

3 3 Constants 3 3 ! Intro#$ction: A 9:9 "onstant is a #aria&le that "annot &e "hange' a$ter the initial #alue is assigne' 'uring the exe"ution o$ the s"ri,t% ex"e,t $or !agi" "onstants% *hi"h are not reall "onstants. Rou "reate a "onstant #aria&le using the 'e$ine 12 $un"tion. .he $un"tion a""e,ts 2 argu!ents. .he $irst !ust &e a string an' re,resents the na!e *hi"h *ill &e use' to a""ess the "onstant. A "onstant na!e is "ase@sensiti#e & 'e$ault an' & "on#ention% are al*a s u,,er"ase. A #ali' "onstant na!e starts *ith a letter or un'ers"ore% $ollo*e' & ho*e#er% & an "o!&ination o$ letters% nu!&ers or un'ers"ores% "a,ital letters an' un'ers"ore s !&ols are use'. "on#ention onl

Constant na!es !ust &e in 4uotes *hen the are 'e$ine'. .he se"on' argu!ent is the #alue o$ the "onstant an' "an &e a string or nu!&ers an' "an &e set ex,li"itl or as as the result o$ a $un"tion or e4uation. .he s"o,e o$ a "onstant is glo&al% *hi"h !eans that ou "an a""ess "onstants an *here in our s"ri,t *ithout regar' to s"o,e. 9:9 has !an ,re@'e$ine' "onstants that "an &e use' in our s"ri,ts. FG,h, 'e$ine 15SECE5% 5Sri Esh*ar College 6$ Engineering52J 73 Sree Sakthi Engineering College

e"ho SECEJ GH 3 3 + Magic Constants 7agi" "onstants% as the are "alle'% are not a"utall "onstants &ut e$$e"ti#el &eha#e like "onstants an' are ,re@'e$ine'. 7agi" "onstants use the sa!e na!ing "on#ention as 9:9 "onstants. .he $ull list o$ !agi" "onstants "an &e $oun' here. .here are 7 !agi" "onstants that "hange 'e,en'ing on *here the are use'. .he are liste' &elo*. na!e PPL;8EPP PP>;LEPP 'es"ri,tion .he "urrent line nu!&er o$ the $ile. .he $ull ,ath an' $ilena!e o$ the $ile. ;$ use' insi'e an in"lu'e% the na!e o$ the in"lu'e' $ile is returne'. Sin"e 9:9 4.0.2% PP>;LEPP al*a s "ontains an a&solute ,ath *ith s !links resol#e' *hereas in ol'er #ersions it "ontaine' relati#e ,ath un'er so!e "ir"u!stan"es. PP=;0PP .he 'ire"tor o$ the $ile. ;$ use' insi'e an in"lu'e% the

'ire"tor o$ the in"lu'e' $ile is returne'. .his is e4ui#alent to 'irna!e1PP>;LEPP2. .his 'ire"tor na!e 'oes not ha#e a trailing slash unless it is the root 'ire"tor . 1A''e' in 9:9 5.3.0.2 PP>+8C.;68PP .he $un"tion na!e. 1A''e' in 9:9 4.3.02 As o$ 9:9 5 this "onstant returns the $un"tion na!e as it *as 'e"lare' 1"ase@sensiti#e2. ;n 9:9 4 its #alue is al*a s lo*er"ase'.

74 Sree Sakthi Engineering College

PPCLASSPP

.he "lass na!e. 1A''e' in 9:9 4.3.02 As o$ 9:9 5 this "onstant returns the "lass na!e as it *as 'e"lare' 1"ase@ sensiti#e2. ;n 9:9 4 its #alue is al*a s lo*er"ase'.

PP7E.:6=PP

.he "lass !etho' na!e. 1A''e' in 9:9 5.0.02 .he !etho' na!e is returne' as it *as 'e"lare' 1"ase@sensiti#e2.

PP8A7ES9ACEPP

.he na!e o$ the "urrent na!es,a"e 1"ase@sensiti#e2. .his "onstant is 'e$ine' in "o!,ile@ti!e 1A''e' in 9:9 5.3.02

3 / Data T.pe: 9:9 s"ri,ts 'eal *ith 'ata in one $or! or another% usuall store' in #aria&les. 9:9 "an *ork *ith 'i$$erent t ,es o$ 'ata. >or exa!,le% a *hole nu!&er is sai' to ha#e an integer 'ata t ,e% *hile a string o$ text has a string 'ata t ,e.

3 / ! P"P5s scalar #ata t.pes S"alar 'ata is 'ata that onl $eatures 6 s"alar 'ata t ,es/ . ,e ;nteger $loat string uni"o'e =es"ri,tion A *hole nu!&er A $loating ,oint nu!&er Exa!,le #alues 7% @23 7.68% @23.45 "ontains a single #alue. As o$ #ersion 6% 9:9

A se4uen"e o$ "hara"ters 5:ello5% 5a&"123SKN5 A se4uen"e o$ +ni"o'e "hara"ters 5:ello5% 5a&"123SKN5

&inar

A se4uen"e o$ &inar

5:ello5% 5a&"123SKN5 75 Sree Sakthi Engineering College

1non@+ni"o'e2 "hara"ters &oolean Either true or $alse true% $alse

3 / + P"P5s co&po$n# #ata t.pes Co!,oun' 'ata "an "ontain !ulti,le #alues. 9:9 has 2 "o!,oun' 'ata t ,es/ o o Arra @ Can hol' !ulti,le #alues in'exe' & nu!&ers or strings.

6&)e"t @ Can hol' !ulti,le #alues 1,ro,erties2% an' "an also "ontain !etho's 1$un"tions2 $or *orking on ,ro,erties.

An arra or o&)e"t "an "ontain !ulti,le #alues% all a""esse' #ia one #aria&le na!e. (hat-s !ore% those #alues "an the!sel#es &e other arra s or o&)e"ts. .his allo*s ou to "reate 4uite "o!,lex "olle"tions o$ 'ata. 3 0 Operators 6,erators are use' to o,erate on #alues. 3 0 ! Arit1&etic Operators Operat or 3 A''ition xO2 x32 @ Su&tra"tion xO2 5@x L 7ulti,li"ation xO4 xL5 D =i#ision 15D5 3 76 Sree Sakthi Engineering College 20 3 4 Description E,a&ple Res$lt

5D2 T 7o'ulus 5T2 10T8 10T2 33 ;n"re!ent xO5 x33 @@ =e"re!ent xO5 x@@

2.5 1 2 0 xO6

xO4

3 0 + Assign&ent Operators Operator O 3O @O LO DO .O TO E,a&ple xO x3O x@O xLO xDO x.O xTO Is T1e Sa&e As xO xOx3 xOx@ xOxL xOxD xOx. xOxT

3 0 3 Co&parison Operators 6,erator OO IO =es"ri,tion is e4ual to is not e4ual Exa!,le 5OO8 returns $alse 5IO8 returns true 77 Sree Sakthi Engineering College

FH H F HO

is not e4ual is greater than is less than is greater than or e4ual to

5FH8 returns true 5H8 returns $alse 5F8 returns true 5HO8 returns $alse

FO

is less than or e4ual to

5FO8 returns true

6,erator UU

=es"ri,tion an'

Exa!,le xO6 O3 1x F 10 UU returns true H 12

VV

or

xO6 O3 1xOO5 VV $alse OO52 returns

not

xO6 O3 I1xOO 2 returns true

3 0 / Operator Prece#ence LDT :ighest 9re"e'en"e 78 Sree Sakthi Engineering College

3@. F FO H HO O O O IO O UU VV An' W60 60 Lo*est 9re"e'en"e

3 6 State&ents:

3 6 ! P"P Control State&ents 3 6 ! ! i4% elsei4% else i$ 1 2 X Y elsei$ 1 2 X Y else X 79 Sree Sakthi Engineering College

Y 3 6 ! + s'itc1 s*it"h 1 2 X "ase "on'ition1 &reakJ "ase "on'ition2 &reakJ Y 3 6 ! 3 '1ile S ntax/ *hile 1"on'ition2 X Y 3 6 ! / #o 'o X Y *hile 1"on'ition2 3 6 ! 0 4or Exa!,le use o$ the $or state!ent/

80 Sree Sakthi Engineering College

FG,h, $or 1 Nn O 1J Nn F 10J Nn332 X e"ho 5NnFC0H5J Y GH 3 6 ! 6 4oreac1 Mersions o$ 9:9 ,rior to #ersion 4 'o not su,,ort the $orea"h state!ent. .he $ollo*ing "o'e shoul' list the "ontents o$ the arra . FG,h, Ntree O arra 15trunk5% 5&ran"hes5% 5lea#es52J $orea"h 1Ntree as N,art2 X e"ho 5.ree ,art/ N,art 5J Y GH 3 6 ! 7 (rea8 ;s use' to en' the exe"ution o$ a $or% s*it"h% or *hile state!ent 3 6 ! 9 contin$e .his state!ent is use' to ski, the rest o$ the "urrent loo,. FG,h, 81 Sree Sakthi Engineering College

$or 1 Nn O 1J Nn F 10J Nn332 X e"ho 5NnFC0H5J i$ 1Nn OO 52 "ontinueJ e"ho 5.his state!ent is ski,,e' *hen Nn O 5.FC0H5J Y GH .he "ontinue state!ent "an &e gi#en an o,tional ,ara!eter su"h as 5"ontinue 25 telling it ho* !an le#els o$ loo,s to ski,.

3 7 *$nctions 3 7 ! De4inition A $un"tion is a &lo"k o$ "o'e that ,er$or!s a s,e"i$i" task. ;t has a na!e an' it is reusa&le. .o kee, the s"ri,t $ro! &eing exe"ute' *hen the ,age loa's% ou "an ,ut it into a $un"tion. A $un"tion *ill &e exe"ute' & a "all to the $un"tion. Rou !a "all a $un"tion $ro! an *here *ithin a ,age.

=.1.# User8defined functions A function may (e defined using synta' suc% as t%e follo ing:
9:9 $un"tion gui'elines/

Ai#e the $un"tion a na!e that re$le"ts *hat the $un"tion 'oes .he $un"tion na!e "an start *ith a letter or un'ers"ore 1not a nu!&er2

E,a&ple A si!,le $un"tion that *rites ! na!e *hen it is "alle'/ 82 Sree Sakthi Engineering College

Fht!lH F&o' H FG,h, $un"tion *rite8a!e12 X e"ho 5Zai Bi! 0e$snes5J Y e"ho 57 na!e is 5J *rite8a!e12J GH FD&o' H FDht!lH O$tp$t: 7 na!e is Zai Bi! 0e$snes

3 7 3 P"P *$nctions : A##ing para&eters .o a'' !ore $un"tionalit to a $un"tion% *e "an a'' ,ara!eters. A ,ara!eter is )ust like a #aria&le.9ara!eters are s,e"i$ie' a$ter the $un"tion na!e% insi'e the ,arentheses. E,a&ple ! .he $ollo*ing exa!,le *ill *rite 'i$$erent $irst na!es% &ut e4ual last na!e/ Fht!lH F&o' H FG,h, $un"tion *rite8a!e1N$na!e2 X e"ho N$na!e . 5 0e$snes.F&r DH5J 83 Sree Sakthi Engineering College

Y e"ho 57 na!e is 5J *rite8a!e15Zai Bi!52J e"ho 57 sister-s na!e is 5J *rite8a!e15:ege52J e"ho 57 &rother-s na!e is 5J *rite8a!e15Stale52J GH FD&o' H FDht!lH 6ut,ut/ 7 na!e is Zai Bi! 0e$snes. 7 sister-s na!e is :ege 0e$snes. 7 &rother-s na!e is Stale 0e$snes.

3 7 / P"P *$nctions : Ret$rn )al$es .o let a $un"tion return a #alue% use the return state!ent. E,a&ple Fht!lH F&o' H FG,h, $un"tion a''1Nx%N 2 X NtotalONx3N J return NtotalJ Y e"ho 51 3 16 O 5 . a''11%162J GH 84 Sree Sakthi Engineering College

FD&o' H FDht!lH 6ut,ut/ 1 3 16 O 17

3 7 0 *$nctions 'it1in 4$nctions FG,h, $un"tion $oo12 X $un"tion &ar12 X e"ho 5; 'on-t exist until $oo12 is "alle'.[n5J Y Y DL (e "an-t "all &ar12 et sin"e it 'oesn-t exist. LD $oo12J DL 8o* *e "an "all &ar12% $oo12-s ,ro"essesing has !a'e it a""essi&le. LD &ar12J GH

All $un"tions an' "lasses in 9:9 ha#e the glo&al s"o,e @ the "an &e "alle' outsi'e a $un"tion e#en i$ the *ere 'e$ine' insi'e an' #i"e #ersa. 9:9 su,,orts ,assing argu!ents & #alue 1the 'e$ault2% ,assing & re$eren"e% an' 'e$ault argu!ent #alues. Maria&le@length argu!ent lists are su,,orte' onl in 85 Sree Sakthi Engineering College

9:9 4 an' laterJ see Maria&le@length argu!ent lists an' the $un"tion re$eren"es $or 4$nc;n$&;args23% 4$nc;get;arg23% an' 4$nc;get;args23 $or !ore in$or!ation. 4$nc;n$&;args: $un"Pnu!Pargs @@ 0eturns the nu!&er o$ argu!ents ,asse' to the $un"tion Description int 4$nc;n$&;args 1 #oi' 2 Aets the nu!&er o$ argu!ents ,asse' to the $un"tion. .his $un"tion !a &e use' in "on)un"tion *ith 4$nc;get;arg23 an' 4$nc;get;args23 to allo* user@'e$ine' $un"tions to a""e,t #aria&le@length argu!ent lists. 3 7 6 Ret$rn -al$es 0eturns the nu!&er o$ argu!ents ,asse' into the "urrent user@'e$ine' $un"tion. Errors<E,ceptions Aenerates a *arning i$ "alle' $ro! outsi'e o$ a user@'e$ine' $un"tion. E,a&ples E,a&ple FG,h, $un"tion $oo12 X Nnu!args O $un"Pnu!Pargs12J e"ho 58u!&er o$ argu!ents/ Nnu!args[n5J Y $oo11% 2% 32J DD 9rints -8u!&er o$ argu!ents/ 386 Sree Sakthi Engineering College

GH

funcE(etEar(@
$un"PgetParg @@ 0eturn an ite! $ro! the argu!ent list

Description
!ixe' 4$nc;get;arg 1 int argPnu! 2

Gets t%e specified argument from a user)defined function0s argument list. -%is function may (e used in con4unction it% funcE(etEar(sRD and funcEnu-Ear(sRD to allo user)defined functions to accept varia(le)lengt% argument lists. =.1.1 !ara-eters argYnum -%e argument offset. /unction arguments are counted starting from .ero. Return Ka"ues Geturns t%e specified argument* or F!LS" on error. 0rrors:0=ceptions Generates a arning if called from outside of a user)defined function* or if arg<num is greater t%an t%e num(er of arguments actually passed. 0=a-p"es 0=a-p"e 1. funcE(etEar(RD e=a-p"e
NO h Gun/tion Goo() P Qnumargs = Gun/<num<args()R e/ho S(um1er oG arguments: QnumargsN1r T>UnSR iG (Qnumargs >= 2) P e/ho SSe/ond argument is: S - Gun/<get<arg(1) - SN1r T>UnSR V V Goo (1? 2? 3)R O>

87 Sree Sakthi Engineering College

88 Sree Sakthi Engineering College

89 Sree Sakthi Engineering College

90 Sree Sakthi Engineering College

91 Sree Sakthi Engineering College

92 Sree Sakthi Engineering College

93 Sree Sakthi Engineering College

94 Sree Sakthi Engineering College

95 Sree Sakthi Engineering College

96 Sree Sakthi Engineering College

97 Sree Sakthi Engineering College

98 Sree Sakthi Engineering College

99 Sree Sakthi Engineering College

100 Sree Sakthi Engineering College

101 Sree Sakthi Engineering College

copy it to a different location:


FG,h, i$ 111NP>;LES\5$ile5]\5t ,e5] OO 5i!ageDgi$52 VV 1NP>;LES\5$ile5]\5t ,e5] OO 5i!ageD),eg52 VV 1NP>;LES\5$ile5]\5t ,e5] OO 5i!ageD,),eg522 UU 1NP>;LES\5$ile5]\5siEe5] F 2000022 X i$ 1NP>;LES\5$ile5]\5error5] H 02 X e"ho 50eturn Co'e/ 5 . NP>;LES\5$ile5]\5error5] . 5F&r DH5J Y else X e"ho 5+,loa'/ 5 . NP>;LES\5$ile5]\5na!e5] . 5F&r DH5J e"ho 5. ,e/ 5 . NP>;LES\5$ile5]\5t ,e5] . 5F&r DH5J e"ho 5SiEe/ 5 . 1NP>;LES\5$ile5]\5siEe5] D 10242 . 5 Z&F&r DH5J e"ho 5.e!, $ile/ 5 . NP>;LES\5$ile5]\5t!,Pna!e5] . 5F&r DH5J i$ 1$ilePexists15u,loa'D5 . NP>;LES\5$ile5]\5na!e5]22 X e"ho NP>;LES\5$ile5]\5na!e5] . 5 alrea' exists. 5J Y else X !o#ePu,loa'e'P$ile1NP>;LES\5$ile5]\5t!,Pna!e5]% 5u,loa'D5 . NP>;LES\5$ile5]\5na!e5]2J e"ho 5Store' in/ 5 . 5u,loa'D5 . NP>;LES\5$ile5]\5na!e5]J Y Y Y else X e"ho 5;n#ali' $ile5J Y GH

-%e script a(ove c%ec+s if t%e file already e'ists* if it does not* it copies t%e file to t%e specified
102 Sree Sakthi Engineering College

folder. P"P #irector. listing "any times e %ave to display t%e list of files in a directory. 5e can +eep t%e script in any location and (y using t%e file pat% e can display t%e files inside t%e directory. CC open t%e current directory (y opendir N%andleVopendir13.32K %ile 11Nfile V readdir1N%andle22bVVfalse2 ^ ec%o 3Nfile T(rP3K ` closedir1N%andle2K

3 !+ P"P an# S=L #ata(ase:

$.1#.1 Create a Connection to a 4)SN2 Database ?efore you can access data in a data(ase* you must create a connection to t%e data(ase. In #J#* t%is is done it% t%e mys,lYconnect12 function. S)nta=
! s4lP"onne"t1ser#erna!e%userna!e%,ass*or'2J 103 Sree Sakthi Engineering College

Para&eter ser#erna!e

Description 6,tional. S,e"i$ies the ser#er to "onne"t to. =e$ault #alue is 5lo"alhost/33065 6,tional. S,e"i$ies the userna!e to log in *ith. =e$ault #alue is the na!e o$ the user that o*ns the ser#er ,ro"ess 6,tional. S,e"i$ies the ,ass*or' to log in *ith. =e$ault is 55

userna!e

,ass*or'

Note@ -%ere are more availa(le parameters* (ut t%e ones listed a(ove are t%e most important. 0=a-p"e In t%e follo ing e'ample e store t%e connection in a varia(le 1Ncon2 for later use in t%e script. -%e 3die3 part ill (e e'ecuted if t%e connection fails:
FG,h, N"on O ! s4lP"onne"t15lo"alhost5%5,eter5%5a&"12352J i$ 1IN"on2 X 'ie1-Coul' not "onne"t/ - . ! s4lPerror122J Y DD so!e "o'e GH

$.1#.# C"osin( a Connection -%e connection ill (e closed automatically %en t%e script ends. -o close t%e connection (efore* use t%e mys,lYclose12 function:

104 Sree Sakthi Engineering College

FG,h, N"on O ! s4lP"onne"t15lo"alhost5%5,eter5%5a&"12352J i$ 1IN"on2 X 'ie1-Coul' not "onne"t/ - . ! s4lPerror122J Y DD so!e "o'e ! s4lP"lose1N"on2J GH

$.1#.$ Create a Database -%e $G@A-@ &A-A?AS@ statement is used to create a data(ase in "yS[L. S)nta=
C0EA.E =A.ACASE 'ata&asePna!e

-o get #J# to e'ecute t%e statement a(ove e must use t%e mys,lY,uery12 function. -%is function is used to send a ,uery or command to a "yS[L connection. 0=a-p"e -%e follo ing e'ample creates a data(ase called 3myYd(3:
FG,h, N"on O ! s4lP"onne"t15lo"alhost5%5,eter5%5a&"12352J i$ 1IN"on2 X 'ie1-Coul' not "onne"t/ - . ! s4lPerror122J Y i$ 1! s4lP4uer 15C0EA.E =A.ACASE ! P'&5%N"on22 X e"ho 5=ata&ase "reate'5J Y else 105 Sree Sakthi Engineering College

X e"ho 5Error "reating 'ata&ase/ 5 . ! s4lPerror12J Y ! s4lP"lose1N"on2J GH

$.1#.' Create a Tab"e -%e $G@A-@ -A?L@ statement is used to create a ta(le in "yS[L. S)nta=
C0EA.E .ACLE ta&lePna!e 1 "olu!nPna!e1 'ataPt ,e% "olu!nPna!e2 'ataPt ,e% "olu!nPna!e3 'ataPt ,e% .... 2

5e must add t%e $G@A-@ -A?L@ statement to t%e mys,lY,uery12 function to e'ecute t%e command. 0=a-p"e -%e follo ing e'ample creates a ta(le named 3#ersons3* it% t%ree columns. -%e column names ill (e 3/irstName3* 3LastName3 and 3Age3:
FG,h, N"on O ! s4lP"onne"t15lo"alhost5%5,eter5%5a&"12352J i$ 1IN"on2 X 'ie1-Coul' not "onne"t/ - . ! s4lPerror122J Y DD Create 'ata&ase i$ 1! s4lP4uer 15C0EA.E =A.ACASE ! P'&5%N"on22 X e"ho 5=ata&ase "reate'5J 106 Sree Sakthi Engineering College

Y else X e"ho 5Error "reating 'ata&ase/ 5 . ! s4lPerror12J Y DD Create ta&le ! s4lPsele"tP'&15! P'&5% N"on2J Ns4l O 5C0EA.E .ACLE 9ersons 1 >irst8a!e #ar"har1152% Last8a!e #ar"har1152% Age int 25J DD Exe"ute 4uer ! s4lP4uer 1Ns4l%N"on2J ! s4lP"lose1N"on2J GH

$.1#., Insert Data into a Database Tab"e -%e INS@G- IN-O statement is used to add ne records to a data(ase ta(le. S)nta= It is possi(le to rite t%e INS@G- IN-O statement in t o forms. -%e first form doesn0t specify t%e column names %ere t%e data ill (e inserted* only t%eir values:
;8SE0. ;8.6 ta&lePna!e MAL+ES 1#alue1% #alue2% #alue3%...2

-%e second form specifies (ot% t%e column names and t%e values to (e inserted:
;8SE0. ;8.6 ta&lePna!e 1"olu!n1% "olu!n2% "olu!n3%...2 MAL+ES 1#alue1% #alue2% #alue3%...2 107 Sree Sakthi Engineering College

-o get #J# to e'ecute t%e statements a(ove e must use t%e mys,lY,uery12 function. -%is function is used to send a ,uery or command to a "yS[L connection. 0=a-p"e In t%e previous c%apter e created a ta(le named 3#ersons3* it% t%ree columnsK 3/irstname3* 3Lastname3 and 3Age3. 5e ill use t%e same ta(le in t%is e'ample. -%e follo ing e'ample adds t o ne records to t%e 3#ersons3 ta(le:
FG,h, N"on O ! s4lP"onne"t15lo"alhost5%5,eter5%5a&"12352J i$ 1IN"on2 X 'ie1-Coul' not "onne"t/ - . ! s4lPerror122J Y ! s4lPsele"tP'&15! P'&5% N"on2J ! s4lP4uer 15;8SE0. ;8.6 9ersons 1>irst8a!e% Last8a!e% Age2 MAL+ES 1-9eter-% -Ari$$in-% -35-252J ! s4lP4uer 15;8SE0. ;8.6 9ersons 1>irst8a!e% Last8a!e% Age2 MAL+ES 1-Alenn-% -?uag!ire-% -33-252J ! s4lP"lose1N"on2J GH

$.1#./ Se"ect Data Fro- a Database Tab"e -%e S@L@$- statement is used to select data from a data(ase. S)nta=
SELEC. "olu!nPna!e1s2 >067 ta&lePna!e

-o get #J# to e'ecute t%e statement a(ove e must use t%e mys,lY,uery12 function. -%is function is used to send a ,uery or command to a "yS[L connection.
108 Sree Sakthi Engineering College

0=a-p"e -%e follo ing e'ample selects all t%e data stored in t%e 3#ersons3 ta(le 1-%e W c%aracter selects all t%e data in t%e ta(le2:
FG,h, N"on O ! s4lP"onne"t15lo"alhost5%5,eter5%5a&"12352J i$ 1IN"on2 X 'ie1-Coul' not "onne"t/ - . ! s4lPerror122J Y ! s4lPsele"tP'&15! P'&5% N"on2J Nresult O ! s4lP4uer 15SELEC. L >067 9ersons52J *hile1Nro* O ! s4lP$et"hParra 1Nresult22 X e"ho Nro*\->irst8a!e-] . 5 5 . Nro*\-Last8a!e-]J e"ho 5F&r DH5J Y ! s4lP"lose1N"on2J GH

3 !3 LDAP an# LDAP:

$.1$.1 Introduction L&A# is t%e Lig%t eig%t &irectory Access #rotocol* and is a protocol used to access 3&irectory Servers3. -%e &irectory is a special +ind of data(ase t%at %olds information in a tree structure. -%e concept is similar to your %ard dis+ directory structure* e'cept t%at in t%is conte't* t%e root directory is 3-%e orld3 and t%e first level su(directories are 3countries3. Lo er levels of
109 Sree Sakthi Engineering College

t%e directory structure contain entries for companies* organisations or places* e find directory entries for people* and per%aps e,uipment or documents. In case you0re not familiar

%ile yet lo er still

it% L&A#* it is a protocol designed to allo ,uic+* efficient

searc%es of directory services. ?uilt around Internet tec%nologies* L&A# ma+es it possi(le to easily update and ,uery directory services over standard -$#CI# connections* and includes a %ost of po erful features* including security* access control* data replication and support for Unicode. -o refer to a file in a su(directory on your %ard dis+* you mig%t use somet%ing li+e: CusrClocalCmyappCdocs -%e for ards slas% mar+s eac% division in t%e reference* and t%e se,uence is read from left to rig%t. -%e e,uivalent to t%e fully ,ualified file reference in L&A# is t%e 3distinguis%ed name3* referred to simply as 3dn3. An e'ample dn mig%t (e: cnVLo%n Smit%*ouVAccounts*oV"y $ompany*cVUS -%e comma mar+s eac% division in t%e reference* and t%e se,uence is read from rig%t to left. 8ou ould read t%is dn as: country V US organi.ation V "y $ompany organi.ationalUnit V Accounts commonName V Lo%n Smit% L&A# support in #J# is not ena(led (y default. 8ou
lda W=)&%X

ill need to use t%e --with-

configuration option %en compiling #J# to ena(le L&A# support. &IG is t%e L&A#

(ase install directory. -o ena(le SASL support* (e sure --with-lda -saslW=)&%X is used* and t%at sasl-h e'ists on t%e system. $.1$.# !redefined Constants -%e constants (elo are defined (y t%is e'tension* and ill only (e availa(le %en t%e e'tension %as eit%er (een compiled into #J# or dynamically loaded at runtime. 2D*!ED0R0FEN0K0R 1integer2 2D*!ED0R0FES0*RC>IN. 1integer2
110 Sree Sakthi Engineering College

2D*!ED0R0FEFINDIN. 1integer2 2D*!ED0R0FE*2W*9S 1integer2 2D*!EO!TED0R0F 1integer2

$.1$.$ Usin( the !>! 2D*! ca""s ?efore you can use t%e L&A# calls you ill need to +no ..

-%e name or address of t%e directory server you ill use -%e 3(ase dn3 of t%e server 1t%e part of t%e orld directory t%at is %eld on t%is server* %ic% could (e 3oV"y $ompany*cVUS32 5%et%er you need a pass ord to access t%e server 1many servers ill provide read access for an 3anonymous (ind3 (ut re,uire a pass ord for anyt%ing else2

-%e typical se,uence of L&A# calls you ill ma+e in an application ill follo t%is pattern: ldapYconnect12 _ ldapY(ind12 _ do somet%ing li+e searc% or update t%e directory and display t%e results _ ldapYclose12 CC 3logout3 $.1$.' 2D*! Functions
l'a,P8859PtoPt61 ^ .ranslate 8859 "hara"ters to t61 "hara"ters l'a,Pa'' ^ A'' entries to L=A9 'ire"tor l'a,P&in' ^ Cin' to L=A9 'ire"tor l'a,P"lose ^ Alias o$ l'a,Pun&in' l'a,P"o!,are ^ Co!,are #alue o$ attri&ute $oun' in entr s,e"i$ie' *ith =8 111 Sree Sakthi Engineering College

CC esta(lis% connection to server CC anonymous or aut%enticated 3login3

ldapYconnect a $onnect to an L&A# server


3 !/ P"P Connecti)it.: 3 !/ ! E,a&ple Progra& FG,h, TT 1asi/ seEuen/e with 8)*I is /onne/t? 1ind? sear/h? inter ret sear/h TT result? /lose /onne/tion e/ho SNh3>8)*I EuerC testNTh3>SR e/ho S6onne/ting ---SR Qds=lda </onne/t(Slo/alhostS)R TT must 1e a valid 8)*I serverY e/ho S/onne/t result is S - Qds - SN1r T>SR iG (Qds) P e/ho S,inding ---SR Qr=lda <1ind(Qds)R

TT this is an SanonCmousS 1ind? tC i/allC TT read-onlC a//ess e/ho S,ind result is S - Qr - SN1r T>SR e/ho SSear/hing Gor (sn=SF) ---SR TT Sear/h surname entrC Qsr=lda <sear/h(Qds? So=>C 6om anC? /=7SS? Ssn=SFS)R e/ho SSear/h result is S - Qsr - SN1r T>SR

e/ho S(um1er oG entires returned is S - lda </ount<entries(Qds? Qs r) - SN1r T>SR e/ho SKetting entries ---N >SR QinGo = lda <get<entries(Qds? Qsr)R e/ho S)ata Gor S - QinGoWS/ountSX - S items returned:N >SR Gor (Qi=0R QiNQinGoWS/ountSXR Qi!!) P e/ho Sdn is: S - QinGoWQiXWSdnSX - SN1r T>SR e/ho SGirst /n entrC is: S - QinGoWQiXWS/nSXW0X - SN1r T>SR e/ho SGirst email entrC is: S - QinGoWQiXWSmailSXW0X - SN1r T> Nhr T>SR V e/ho S6losing /onne/tionSR 112 Sree Sakthi Engineering College

lda </lose(Qds)R V else P e/ho SNh4>7na1le to /onne/t to 8)*I serverNTh4>SR V O>

3 !0 Sen#ing an# Recei)ing E:&ails: 3 !0 ! Intro#$ction: E!ail is the !ost ,o,ular ;nternet ser#i"e to'a . A ,lent o$ e!ails are sent an' 'eli#ere' ea"h 'a .

Description
&ool &ail 1 string to% string su&)e"t% string !essage \% string a''itionalPhea'ers \% string a''itionalP,ara!eters]] 2

Sends an email. !ara-eters to Geceiver* or receivers of t%e mail. -%e formatting of t%is string must comply it% G/$ 7977. Some e'amples are:
userSexa!,le."o! userSexa!,le."o!% anotheruserSexa!,le."o! +ser FuserSexa!,le."o!H +ser FuserSexa!,le."o!H% Another +ser FanotheruserSexa!,le."o!H

su(4ect Su(4ect of t%e email to (e sent.


113 Sree Sakthi Engineering College

Return Ka"ues Geturns #$%" if t%e mail as successfully accepted for delivery* F!LS" ot%er ise. It is important to note t%at 4ust (ecause t%e mail as accepted for delivery* it does NO- mean t%e mail ill actually reac% t%e intended destination. $.1,.# !>! CodeRSer%er sideD 0=a-p"e for Sendin( -ai". Using -ai"RD to send a simple email:
NO h TT +he message Qmessage = S8ine 1Un8ine 2Un8ine 3SR TT &n /ase anC oG our lines are larger than 70 /hara/ters? we should use word wra () Qmessage = wordwra (Qmessage? 70)R TT Send mail(@/aGGinated@e2am le-/om@? @>C Su15e/t@? Qmessage)R O>

0=a-p"e for Sendin( -ai" with e=tra headers. -%e addition of (asic %eaders* telling t%e "UA t%e /rom and Geply)-o addresses:
NO h Qto = @no1odC@e2am le-/om@R Qsu15e/t = @the su15e/t@R Qmessage = @hello@R Qheaders = @=rom: we1master@e2am le-/om@ - SUrUnS @%e lC-+o: we1master@e2am le-/om@ - SUrUnS @Z->ailer: IJIT@ O> h version()R mail(Qto? Qsu15e/t? Qmessage? Qheaders)R

$.1,.$ >T42 codeRC"ient SideD


E,a&ple 4or Sen#ing "TML e&ail 114 Sree Sakthi Engineering College

;t is also ,ossi&le to sen' :.7L e!ail *ith &ail23. FG,h, DD !ulti,le re"i,ients Nto O -ai'anSexa!,le."o!- . -% -J DD note the "o!!a Nto .O -*eESexa!,le."o!-J DD su&)e"t Nsu&)e"t O -Cirth'a 0e!in'ers $or August-J DD !essage N!essage O Fht!lH Fhea'H FtitleHCirth'a 0e!in'ers $or AugustFDtitleH FDhea'H F&o' H F,H:ere are the &irth'a s u,"o!ing in AugustIFD,H Fta&leH FtrH FthH9ersonFDthHFthH=a FDthHFthH7onthFDthHFthHRearFDthH FDtrH FtrH Ft'HBoeFDt'HFt'H3r'FDt'HFt'HAugustFDt'HFt'H1970FDt'H FDtrH FtrH Ft'HSall FDt'HFt'H17thFDt'HFt'HAugustFDt'HFt'H1973FDt'H FDtrH FDta&leH FD&o' H FDht!lH DD .o sen' :.7L !ail% the Content@t ,e hea'er !ust &e set Nhea'ers O -7;7E@Mersion/ 1.0- . 5[r[n5J 115 Sree Sakthi Engineering College

Nhea'ers .O -Content@t ,e/ textDht!lJ "harsetOiso@8859@1- . 5[r[n5J DD A''itional hea'ers Nhea'ers .O -.o/ 7ar F!ar Sexa!,le."o!H% Zell Fkell Sexa!,le."o!H- . 5[r[n5 J Nhea'ers .O ->ro!/ Cirth'a 0e!in'er F&irth'a Sexa!,le."o!H- . 5[r[n5J Nhea'ers .O -C"/ &irth'a ar"hi#eSexa!,le."o!- . 5[r[n5J Nhea'ers .O -C""/ &irth'a "he"kSexa!,le."o!- . 5[r[n5J DD 7ail it !ail1Nto% Nsu&)e"t% N!essage% Nhea'ers2J GH

3 !6 De($gging an# error 1an#ling: 3 !6 ! De($gging 9:9 'oes not ha#e an internal 'e&ugging $a"ilit . Rou "an use one o$ the external 'e&uggers though. .he QE8= ;=E in"lu'es a 'e&ugger.

$.1/.1.1 Usin( the Debu((er


.he internal 'e&ugger in 9:9 3 is use$ul $or tra"king 'o*n e#asi#e &ugs. .he 'e&ugger *orks & "onne"ting to a .C9 ,ort $or e#er ti!e 9:9 3 starts u,. All error !essages $ro! that re4uest *ill &e sent to this .C9 "onne"tion. .his in$or!ation is inten'e' $or 5'e&ugging ser#er5 that "an run insi'e an ;=E or ,rogra!!a&le e'itor 1su"h as E!a"s2. :o* to set u, the 'e&ugger/ 1. Set u, a .C9 ,ort $or the 'e&ugger in the "on$iguration $ile 1'e&ugger.,ort2 an' ena&le it 1'e&ugger.ena&le'2. 2. Set u, a .C9 listener on that ,ort so!e*here 1$or exa!,le soc8et :l :s !/>> on +nix s ste!s2.

116 Sree Sakthi Engineering College

3. ;n our "o'e% run 5'e&uggerPon1host25% *here host is the ;9 nu!&er or na!e o$ the host running the .C9 listener. 8o*% all *arnings% noti"es et". *ill sho* u, on that listener so"ket% e#en i$ ou turne' the! o$$ *ith error;reporting23.

$.1/.1.# Debu((er !rotoco"


.he 9:9 3 'e&ugger ,roto"ol is line@&ase'. Ea"h line has a t ,e% an' se#eral lines "o!,ose a !essage. Ea"h !essage starts *ith a line o$ the t ,e start an' ter!inates *ith a line o$ the t ,e en'. 9:9 3 !a sen' lines $or 'i$$erent !essages si!ultaneousl . A line has this $or!at/ 'ate ti!e host1,i'2 t ,e/ !essage@'at 'ate =ate in ;S6 8601 $or!at 1 ti!e .i!e in"lu'ing !i"rose"on's/ hh/!!/uuuuuu host =8S na!e or ;9 a''ress o$ the host *here the s"ri,t error *as generate'. ,i' 9;= 1,ro"ess i'2 on host o$ the ,ro"ess *ith the 9:9 3 s"ri,t that generate' this error. @!!@''2

t ,e

117 Sree Sakthi Engineering College

. ,e o$ line. .ells the re"ei#ing ,rogra! a&out *hat it shoul' treat the $ollo*ing 'ata as/ 3 !6 ! + De($gger Error T.pes De($gger P"P 3 Internal *arning error ,arse noti"e "ore@error "ore@ *arning unkno*n EP(A08;8A EPE0060 EP9A0SE EP86.;CE EPC60EPE0060 EPC60EP(A08; 8A 1an other2

3 !6 / Con4ig$re options

2ist of core confi(ure options 4isc options ))ena(le)de(ug $ompile it% de(ugging sym(ols. )) it%)layoutV-8#@ Sets %o installed files ill (e laid out. -ype is one of #J# 1default2 or GNU. )) it%)pearV&IG Install #@AG in &IG 1default #G@/IXCli(Cp%p2. )) it%out)pear
118 Sree Sakthi Engineering College

&o not install #@AG. ))ena(le)sigc%ild @na(le #J#0s o n SIG$JL& %andler. !>! options ))ena(le)maintainer)mode @na(le ma+e rules and dependencies not useful 1and sometimes confusing2 to t%e casual installer. )) it%)config)file)pat%V#A-J Sets t%e pat% in %ic% to loo+ for h -ini* defaults to #G@/IXCli(. ))ena(le)safe)mode @na(le safe mode (y default. )) it%)e'ec)dirQV&IGR Only allo e'ecuta(les in &IG %en in safe mode defaults to CusrClocalCp%pC(in. S*!I options -%e follo ing list contains t%e availa(le SA#IHs 1Server *
&nterGa/e2 li/ation Irogramming

for #J#.

)) it%)aolserverV&IG Specify pat% to t%e installed AOLserver. )) it%)ap'sQV/IL@R ?uild s%ared Apac%e module. /IL@ is t%e optional pat%name to t%e Apac%e ap's toolK defaults to ap's. "a+e sure you specify t%e version of ap's t%at is actually installed on your system and NO- t%e one t%at is in t%e apac%e source tar(all. )) it%)apac%eQV&IGR ?uild a static Apac%e module. &IG is t%e top)level Apac%e (uild directory* defaults to
TusrTlo/alTa a/he.

119 Sree Sakthi Engineering College

)) it%)modYc%arset @na(le transfer ta(les for modYc%arset 1Gussian Apac%e2. )) it%)ap's7QV/IL@R ?uild s%ared Apac%e 7.: module. /IL@ is t%e optional pat%name to t%e Apac%e ap's toolK defaults to ap's.

3 !6 + Error "an#ling: .he 'e$ault error han'ling in 9:9 is #er si!,le. An error !essage *ith $ilena!e% line nu!&er an' a !essage 'es"ri&ing the error is sent to the &ro*ser.

3 !6 + ! P"P Error "an#ling (hen "reating s"ri,ts an' *e& a,,li"ations% error han'ling is an i!,ortant ,art. ;$ our "o'e la"ks error "he"king "o'e% our ,rogra! !a look #er un,ro$essional an' ou !a &e o,en to se"urit risks. .his tutorial "ontains so!e o$ the !ost "o!!on error "he"king !etho's in 9:9. (e *ill sho* 'i$$erent error han'ling !etho's/

Si!,le 5'ie125 state!ents Custo! errors an' error triggers Error re,orting

3 !6 + + ?asic Error "an#ling: Using t1e #ie23 4$nction .he $irst exa!,le sho*s a si!,le s"ri,t that o,ens a text $ile/ FG,h, 120 Sree Sakthi Engineering College

N$ileO$o,en15*el"o!e.txt5%5r52J GH ;$ the $ile 'oes not exist ou !ight get an error like this/ @arning/ $o,en1*el"o!e.txt2 \$un"tion.$o,en]/ $aile' to o,en strea!/ 8o su"h $ile or 'ire"tor in C:A'e(4ol#erAtest p1p on line + .o a#oi' that the user gets an error !essage like the one a&o#e% *e test i$ the $ile exist &e$ore *e tr to a""ess it/ FG,h, i$1I$ilePexists15*el"o!e.txt522 X 'ie15>ile not $oun'52J Y else X N$ileO$o,en15*el"o!e.txt5%5r52J Y GH 8o* i$ the $ile 'oes not exist ou get an error like this/ >ile not $oun' .he "o'e a&o#e is !ore e$$i"ient than the earlier "o'e% &e"ause it uses a si!,le error han'ling !e"hanis! to sto, the s"ri,t a$ter the error. :o*e#er% si!,l sto,,ing the s"ri,t is not al*a s the right *a to go. Let-s take a look at alternati#e 9:9 $un"tions $or han'ling errors.

3 !6 + / Creating a C$sto& Error "an#ler Creating a "usto! error han'ler is 4uite si!,le. (e si!,l "reate a s,e"ial $un"tion that "an &e "alle' *hen an error o""urs in 9:9. 121 Sree Sakthi Engineering College

.his $un"tion !ust &e a&le to han'le a !ini!u! o$ t*o ,ara!eters 1error le#el an' error !essage2 &ut "an a""e,t u, to $i#e ,ara!eters 1o,tionall / $ile% line@nu!&er% an' the error "ontext2/ S.nta, errorP$un"tion1errorPle#el%errorP!essage% errorP$ile%errorPline%errorP"ontext2

Para&eter errorPle#el

Description 0e4uire'. S,e"i$ies the error re,ort le#el $or the user@'e$ine' error. 7ust &e a #alue nu!&er. See ta&le &elo* $or ,ossi&le error re,ort le#els

errorP!essage errorP$ile errorPline errorP"ontext

0e4uire'. S,e"i$ies the error !essage $or the user@'e$ine' error 6,tional. S,e"i$ies the $ilena!e in *hi"h the error o""urre' 6,tional. S,e"i$ies the line nu!&er in *hi"h the error o""urre' 6,tional. S,e"i$ies an arra "ontaining e#er #aria&le% an' their #alues% in use *hen the error o""urre'

3 !6 + / Error Report le)els .hese error re,ort le#els are the 'i$$erent t ,es o$ error the user@'e$ine' error han'ler "an &e use' $or/ -al$ e 2

Constant EP(A08;8A

Description 8on@$atal run@ti!e errors. Exe"ution o$ the s"ri,t is not halte'

EP86.;CE

0un@ti!e noti"es. .he s"ri,t $oun' so!ething that 122 Sree Sakthi Engineering College

!ight &e an error% &ut "oul' also ha,,en *hen running a s"ri,t nor!all 256 EP+SE0PE0060 >atal user@generate' error. .his is like an EPE0060 set & the ,rogra!!er using the 9:9 $un"tion triggerPerror12 512 EP+SE0P(A08;8A 8on@$atal user@generate' *arning. .his is like an EP(A08;8A set & the ,rogra!!er using the 9:9 $un"tion triggerPerror12 1024 EP+SE0P86.;CE +ser@generate' noti"e. .his is like an EP86.;CE set & the ,rogra!!er using the 9:9 $un"tion triggerPerror12 4096 EP0EC6ME0ACLEPE0060Cat"ha&le $atal error. .his is like an EPE0060 &ut "an &e "aught & a user 'e$ine' han'le 1see also setPerrorPhan'ler122 8191 EPALL All errors an' *arnings% ex"e,t le#el EPS.0;C. 1EPS.0;C. *ill &e ,art o$ EPALL as o$ 9:9 6.02 8o* lets "reate a $un"tion to han'le errors/ $un"tion "usto!Error1Nerrno% Nerrstr2 X e"ho 5F&HError/FD&H \Nerrno] NerrstrF&r DH5J e"ho 5En'ing S"ri,t5J 'ie12J Y .he "o'e a&o#e is a si!,le error han'ling $un"tion. (hen it is triggere'% it gets the error le#el an' an error !essage. ;t then out,uts the error le#el an' !essage an' ter!inates the s"ri,t. 8o* that *e ha#e "reate' an error han'ling $un"tion *e nee' to 'e"i'e *hen it shoul' &e triggere'. 123 Sree Sakthi Engineering College

3 !6 + 0 Set Error "an#ler .he 'e$ault error han'ler $or 9:9 is the &uilt in error han'ler. (e are going to !ake the $un"tion a&o#e the 'e$ault error han'ler $or the 'uration o$ the s"ri,t. ;t is ,ossi&le to "hange the error han'ler to a,,l $or onl so!e errors% that *a the s"ri,t "an han'le 'i$$erent errors in 'i$$erent *a s. :o*e#er% in this exa!,le *e are going to use our "usto! error han'ler $or all errors/ setPerrorPhan'ler15"usto!Error52J Sin"e *e *ant our "usto! $un"tion to han'le all errors% the setPerrorPhan'ler12 onl nee'e' one ,ara!eter% a se"on' ,ara!eter "oul' &e a''e' to s,e"i$ an error le#el. E,a&ple .esting the error han'ler & tr ing to out,ut #aria&le that 'oes not exist/ FG,h, DDerror han'ler $un"tion $un"tion "usto!Error1Nerrno% Nerrstr2 X e"ho 5F&HError/FD&H \Nerrno] Nerrstr5J Y DDset error han'ler setPerrorPhan'ler15"usto!Error52J DDtrigger error e"ho1Ntest2J GH .he out,ut o$ the "o'e a&o#e shoul' &e so!ething like this/ 124 Sree Sakthi Engineering College

Error: \8] +n'e$ine' #aria&le/ test

3 !6 + 6 Trigger an Error ;n a s"ri,t *here users "an in,ut 'ata it is use$ul to trigger errors *hen an illegal in,ut o""urs. ;n 9:9% this is 'one & the triggerPerror12 $un"tion. E,a&ple ;n this exa!,le an error o""urs i$ the 5test5 #aria&le is &igger than 515/ FG,h, NtestO2J i$ 1NtestH12 X triggerPerror15Malue !ust &e 1 or &elo*52J Y GH .he out,ut o$ the "o'e a&o#e shoul' &e so!ething like this/ Notice/ Malue !ust &e 1 or &elo* in C:A'e(4ol#erAtest p1p on line 6 An error "an &e triggere' an *here ou *ish in a s"ri,t% an' & a''ing a se"on' ,ara!eter% ou "an s,e"i$ *hat error le#el is triggere'. 9ossi&le error t ,es/

EP+SE0PE0060 @ >atal user@generate' run@ti!e error. Errors that "an not &e re"o#ere' $ro!. Exe"ution o$ the s"ri,t is halte' EP+SE0P(A08;8A @ 8on@$atal user@generate' run@ti!e *arning. Exe"ution o$ the s"ri,t is not halte'

125 Sree Sakthi Engineering College

EP+SE0P86.;CE @ =e$ault. +ser@generate' run@ti!e noti"e. .he s"ri,t $oun' so!ething that !ight &e an error% &ut "oul' also ha,,en *hen running a s"ri,t nor!all

E,a&ple ;n this exa!,le an EP+SE0P(A08;8A o""urs i$ the 5test5 #aria&le is &igger than 515. ;$ an EP+SE0P(A08;8A o""urs *e *ill use our "usto! error han'ler an' en' the s"ri,t/ FG,h, DDerror han'ler $un"tion $un"tion "usto!Error1Nerrno% Nerrstr2 X e"ho 5F&HError/FD&H \Nerrno] NerrstrF&r DH5J e"ho 5En'ing S"ri,t5J 'ie12J Y DDset error han'ler setPerrorPhan'ler15"usto!Error5%EP+SE0P(A08;8A2J DDtrigger error NtestO2J i$ 1NtestH12 X triggerPerror15Malue !ust &e 1 or &elo*5%EP+SE0P(A08;8A2J Y GH .he out,ut o$ the "o'e a&o#e shoul' &e so!ething like this/ Error: \512] Malue !ust &e 1 or &elo* En'ing S"ri,t 126 Sree Sakthi Engineering College

3 !7 Sec$rit.:

3 !7 ! Intro#$ction 9:9 is a ,o*er$ul language an' the inter,reter% *hether in"lu'e' in a *e& ser#er as a !o'ule or exe"ute' as a se,arate CA; &inar % is a&le to a""ess $iles% exe"ute "o!!an's an' o,en net*ork "onne"tions on the ser#er. .hese ,ro,erties !ake an thing run on a *e& ser#er inse"ure & 'e$ault. 9:9 is 'esigne' s,e"i$i"all to &e a !ore se"ure language $or *riting CA; ,rogra!s than 9erl or C% an' *ith "orre"t sele"tion o$ "o!,ile@ti!e an' runti!e "on$iguration o,tions% an' ,ro,er "o'ing ,ra"ti"es% it "an gi#e ou exa"tl the "o!&ination o$ $ree'o! an' se"urit . 3 !7 + Installe# as CGI (inar. Possi(le attac8s +sing 9:9 as a CA; &inar is an o,tion $or setu,s that $or so!e reason 'o not *ish to integrate 9:9 as a !o'ule into ser#er so$t*are 1like A,a"he2% or *ill use 9:9 *ith 'i$$erent kin's o$ CA; *ra,,ers to "reate sa$e "hroot an' setui' en#iron!ents $or s"ri,ts. E#en i$ the 9:9 &inar "an &e use' as a stan'alone inter,reter% 9:9 is 'esigne' to ,re#ent the atta"ks this setu, !akes ,ossi&le/

A""essing s ste! $iles/ htt :TTmC-hostT/gi-1inT h OTet/T asswd A""essing an *e& 'o"u!ent on ser#er/ htt :TTmC-hostT/gi1inT h Tse/retTdo/-html

Case !: onl. p$(lic 4iles ser)e# ;$ our ser#er 'oes not ha#e an "ontent that is not restri"te' & ,ass*or' or i, &ase' a""ess "ontrol% there is no nee' $or these "on$iguration o,tions. ;$ our *e& 127 Sree Sakthi Engineering College

ser#er 'oes not allo* ou to 'o re'ire"ts% or the ser#er 'oes not ha#e a *a to "o!!uni"ate to the 9:9 &inar that the re4uest is a sa$el re'ire"te' re4uest% ou "an s,e"i$ the o,tion ::ena(le:4orce:cgi:re#irect to the "on$igure s"ri,t. Case +: $sing cgi 4orce;re#irect .his "o!,ile@ti!e o,tion ,re#ents an one $ro! "alling 9:9 'ire"tl *ith a +0L like htt,/DD! .hostD"gi@&inD,h,Dse"ret'irDs"ri,t.,h,. ;nstea'% 9:9 *ill onl ,arse in this !o'e i$ it has gone through a *e& ser#er re'ire"t rule. Case 3: setting #oc;root or $ser;#ir .o in"lu'e a"ti#e "ontent% like s"ri,ts an' exe"uta&les% in the *e& ser#er 'o"u!ent 'ire"tories is so!eti!es "onsi'ere' an inse"ure ,ra"ti"e. ;$% &e"ause o$ so!e "on$iguration !istake% the s"ri,ts are not exe"ute' &ut 'is,la e' as regular :.7L 'o"u!ents% this !a result in leakage o$ intelle"tual ,ro,ert or se"urit in$or!ation like ,ass*or's. .here$ore !an s sa'!ins *ill ,re$er setting u, another 'ire"tor stru"ture $or s"ri,ts that are a""essi&le onl through the 9:9 CA;% an' there$ore al*a s inter,rete' an' not 'is,la e' as su"h. Case /: P"P parser o$tsi#e o4 'e( tree A #er se"ure o,tion is to ,ut the 9:9 ,arser &inar so!e*here outsi'e o$ the *e& tree o$ $iles. ;n TusrTlo/alT1in% $or exa!,le. .he onl real 'o*nsi'e to this o,tion is that ou *ill no* ha#e to ,ut a line si!ilar to/ [YTusrTlo/alT1inT h as the $irst line o$ an $ile "ontaining 9:9 tags. 3 !7 3 Installe# as an Apac1e &o#$le (hen 9:9 is use' as an A,a"he !o'ule it inherits A,a"he-s user ,er!issions 1t ,i"all those o$ the 5no&o' 5 user2. .his has se#eral i!,a"ts on se"urit an' authoriEation. >or exa!,le% i$ ou are using 9:9 to a""ess a 'ata&ase% unless that 128 Sree Sakthi Engineering College

'ata&ase has &uilt@in a""ess "ontrol% ou *ill ha#e to !ake the 'ata&ase a""essi&le to the 5no&o' 5 user. 3 !7 / *ile s.ste& Sec$rit. 9:9 is su&)e"t to the se"urit &uilt into !ost ser#er s ste!s *ith res,e"t to ,er!issions on a $ile an' 'ire"tor &asis. .his allo*s ou to "ontrol *hi"h $iles in the $iles ste! !a &e rea'. Consi'er the $ollo*ing s"ri,t% *here a user in'i"ates that the -' like to 'elete a $ile in their ho!e 'ire"tor . .his assu!es a situation *here a 9:9 *e& inter$a"e is regularl use' $or $ile !anage!ent% so the A,a"he user is allo*e' to 'elete $iles in the user ho!e 'ire"tories. Exa!,le/ 9oor #aria&le "he"king lea's to.... NO h TT remove a Gile Grom the user@s home dire/torC Qusername = Q<I'S+W@user<su1mitted<name@XR QuserGile = Q<I'S+W@user<su1mitted<Gilename@XR Qhomedir = SThomeTQusernameSR

unlin0(SQhomedirTQuserGileS)R e/ho S+he Gile has 1een deletedYSR O>

E,a&ple: A 4iles.ste& attac8 NO h TT removes a Gile Grom anCwhere on the hard drive that TT the IJI user has a//ess to- &G IJI has root a//ess: Qusername = Q<I'S+W@user<su1mitted<name@XR TT S--Tet/S 129 Sree Sakthi Engineering College

QuserGile = Q<I'S+W@user<su1mitted<Gilename@XR TT S asswdS Qhomedir = SThomeTQusernameSR TT SThomeT--Tet/S

unlin0(SQhomedirTQuserGileS)R TT SThomeT--Tet/T asswdS e/ho S+he Gile has 1een deletedYSR O>

.here are t*o i!,ortant !easures ou shoul' take to ,re#ent these issues.

6nl allo* li!ite' ,er!issions to the 9:9 *e& user &inar . Che"k all #aria&les *hi"h are su&!itte'.

3 !7 0 N$ll (.tes relate# iss$es As 9:9 uses the un'erl ing C $un"tions $or $iles ste! relate' o,erations% it !a han'le null & tes in a 4uite unex,e"te' *a . As null & tes 'enote the en' o$ a string in C% strings "ontaining the! *on-t &e "onsi'ere' entirel &ut rather onl until a null & te o""urs. .he $ollo*ing exa!,le sho*s a #ulnera&le "o'e that 'e!onstrates this ,ro&le!/ E,a&ple +6:0 Script )$lnera(le to n$ll (.tes NO h QGile = Q<K$+W@Gile@XR TT S--T--Tet/T asswdU0S iG (Gile<e2ists(@ThomeTwwwrunT@-QGile-@- h @)) P TT Gile<e2ists will return true as the Gile ThomeTwwwrunT--T--Tet/ T asswd e2ists in/lude @ThomeTwwwrunT@-QGile-@- h @R TT the Gile Tet/T asswd will 1e in/luded V O>

130 Sree Sakthi Engineering College

3 !7 6 Data(ase Sec$rit. 8o*a'a s% 'ata&ases are "ar'inal "o!,onents o$ an *e& &ase' a,,li"ation & ena&ling *e&sites to ,ro#i'e #ar ing ' na!i" "ontent. Sin"e #er sensiti#e or se"ret in$or!ation "an &e store' in a 'ata&ase% ou shoul' strongl "onsi'er ,rote"ting our 'ata&ases. 3 !7 6 ! Designing Data(ases .he $irst ste, is al*a s to "reate the 'ata&ase% unless ou *ant to use one $ro! a thir' ,art . (hen a 'ata&ase is "reate'% it is assigne' to an o*ner% *ho exe"ute' the "reation state!ent. +suall % onl the o*ner 1or a su,eruser2 "an 'o an thing *ith the o&)e"ts in that 'ata&ase% an' in or'er to allo* other users to use it% ,ri#ileges !ust &e grante'. A,,li"ations shoul' ne#er "onne"t to the 'ata&ase as its o*ner or a su,eruser% &e"ause these users "an exe"ute an 4uer at *ill% $or exa!,le% !o'i$ ing the s"he!a 1e.g. 'ro,,ing ta&les2 or 'eleting its entire "ontent 3 !7 6 + Connecting to Data(ase Rou !a *ant to esta&lish the "onne"tions o#er SSL to en"r ,t "lientDser#er "o!!uni"ations $or in"rease' se"urit % or ou "an use ssh to en"r ,t the net*ork "onne"tion &et*een "lients an' the 'ata&ase ser#er. 3 !7 6 3 Encr.pte# Storage Mo#el SSLDSS: ,rote"ts 'ata tra#elling $ro! the "lient to the ser#er% SSLDSS: 'oes not ,rote"t the ,ersistent 'ata store' in a 'ata&ase. SSL is an on@the@*ire ,roto"ol. 6n"e an atta"ker gains a""ess to our 'ata&ase 'ire"tl 1& ,assing the *e&ser#er2% the store' sensiti#e 'ata !a &e ex,ose' or !isuse'% unless the in$or!ation is ,rote"te' & the 'ata&ase itsel$. En"r ,ting the 'ata is a goo' *a to !itigate this threat% &ut #er $e* 'ata&ases o$$er this t ,e o$ 'ata en"r ,tion. 131 Sree Sakthi Engineering College

3 !7 6 / S=L InBection S?L in)e"tion is a "o'e in)e"tion te"hni4ue that ex,loits a se"urit #ulnera&ilit o""urring in the 'ata&ase la er o$ an a,,li"ation. .he #ulnera&ilit is ,resent *hen user in,ut is either in"orre"tl $iltere' $or string literal es"a,e "hara"ters e!&e''e' in S?L state!ents or user in,ut is not strongl t ,e' an' there& unex,e"te'l exe"ute'.

Preventing SQL injection -o protect against S[L in4ection* user input must not directly (e em(edded in S[L statements. Instead* parameteri.ed statements must (e used 1preferred2* or user input must (e carefully escaped or filtered. !ara-eteri<ed state-ents 5it% most development platforms* parameteri.ed statements can (e used t%at or+ it% parameters 1sometimes called place%olders or (ind varia(les2 instead of em(edding user input in t%e statement. 0nforce-ent at the database "e%e" $urrently only t%e J7 &ata(ase @ngine supports t%e a(ility to enforce ,uery parameteri.ation. 0nforce-ent at the codin( "e%e" Using o(4ect)relational mapping li(raries avoids t%e need to rite S[L code. 0scapin( A straig%t)for ard* t%oug% error)prone* ay to prevent in4ections is to escape c%aracters t%at %ave a special meaning in S[L.

3 !7 7 Error Reporting (ith 9:9 se"urit % there are t*o si'es to error re,orting. 6ne is &ene$i"ial to in"reasing se"urit % the other is 'etri!ental.

132 Sree Sakthi Engineering College

A stan'ar' atta"k ta"ti" in#ol#es ,ro$iling a s ste! & $ee'ing it i!,ro,er 'ata% an' "he"king $or the kin's% an' "ontexts% o$ the errors *hi"h are returne'. Attac8ing -aria(les 'it1 a c$sto& "TML page NGorm method=S ostS a/tion=Satta/0targetO username=1adGoo\am R assword=1adGooS> Nin ut tC e=ShiddenS name=SusernameS value=S1adGooS T> Nin ut tC e=ShiddenS name=S asswordS value=S1adGooS T> NTGorm> E,ploiting co&&on #e($gging )aria(les NGorm method=S ostS a/tion=Satta/0targetO errors=B\am Rshowerrors=1\am Rde1ug=1S> Nin ut tC e=ShiddenS name=SerrorsS value=SBS T> Nin ut tC e=ShiddenS name=SshowerrorsS value=S1S T> Nin ut tC e=ShiddenS name=Sde1ugS value=S1S T> NTGorm> 3 !7 9 Using Register Glo(als:

-%e registerYglo(als setting controls %o varia(les. 5%en on* registerYglo(als initiali.ation means

you access form* server* and environment

varia(les. ?y default t%is varia(le is set to Off* re,uiring you to use special arrays to access t%ese ill in4ect your scripts it% all sorts of varia(les* li+e as a difficult decision* (ut t%e

re,uest varia(les from J-"L forms. -%is coupled it% t%e fact t%at #J# doesn0t re,uire varia(le riting insecure code is t%at muc% easier. It #J# community decided to disa(le t%is directive (y default. 5%en on* people use varia(les yet really don0t +no for sure %ere t%ey come from and can only assume. Internal varia(les t%at are
133 Sree Sakthi Engineering College

defined in t%e script itself get mi'ed up registerYglo(als c%anges t%is.


3 !7 C User S$(&itte# Data:

it% re,uest data sent (y users and disa(ling

.he greatest *eakness in !an 9:9 ,rogra!s is not inherent in the language itsel$% &ut !erel an issue o$ "o'e not &eing *ritten *ith se"urit in !in'. >or this reason% ou shoul' al*a s take the ti!e to "onsi'er the i!,li"ations o$ a gi#en ,ie"e o$ "o'e% to as"ertain the ,ossi&le 'a!age i$ an unex,e"te' #aria&le is su&!itte' to it. Dangero$s -aria(le Usage NO h TT remove a Gile Grom the user@s home dire/torC--- or maC1e TT some1odC else@sO unlin0 (Qevil<var)R TT Lrite logging oG their a//ess--- or maC1e an Tet/T asswd entrCO Gwrite (QG ? Qevil<var)R TT $2e/ute something trivial-- or rm -rG FO sCstem (Qevil<var)R e2e/ (Qevil<var)R O>

3 !7 !> Magic =$otes: 7agi" ?uotes is a ,ro"ess that auto!agi"all es"a,es in"o!ing 'ata to the 9:9 s"ri,t. ;t-s ,re$erre' to "o'e *ith !agi" 4uotes o$$ an' to instea' es"a,e the 'ata at runti!e% as nee'e'. 134 Sree Sakthi Engineering College

@1at are Magic =$otes (hen on% all @ 1single@4uote2% S 1'ou&le 4uote2% U 1&a"kslash2 an' (788 "hara"ters are es"a,e' *ith a &a"kslash auto!ati"all . .his is i'enti"al to *hat a##slas1es23 'oes. .here are three !agi" 4uote 'ire"ti#es/

!agi"P4uotesPg," A$$e"ts :..9 0e4uest 'ata 1AE.% 96S.% an' C66Z;E2. Cannot &e set at runti!e% an' 'e$aults to on in 9:9. See also get;&agic;D$otes;gpc23.

!agi"P4uotesPrunti!e ;$ ena&le'% !ost $un"tions that return 'ata $ro! an external sour"e% in"lu'ing 'ata&ases an' text $iles% *ill ha#e 4uotes es"a,e' *ith a &a"kslash. Can &e set at runti!e% an' 'e$aults to o$$ in 9:9. See also set;&agic;D$otes;r$nti&e23 an' get;&agic;D$otes;r$nti&e23.

!agi"P4uotesPs &ase ;$ ena&le'% a single@4uote is es"a,e' *ith a single@4uote instea' o$ a &a"kslash. ;$ on% it "o!,letel o#erri'es !agi"P4uotesPg,". :a#ing &oth 'ire"ti#es ena&le' !eans onl single 4uotes are es"a,e' as @@. =ou&le 4uotes% &a"kslashes an' 8+LL-s *ill re!ain untou"he' an' unes"a,e'. See also ini;get23 $or retrie#ing its #alue. 135 Sree Sakthi Engineering College

@1. #i# 'e $se Magic =$otes +se$ul $or &eginners o 7agi" 4uotes are i!,le!ente' in 9:9 to hel, "o'e *ritten & &eginners $ro! &eing 'angerous. Although S?L ;n)e"tion is still ,ossi&le *ith !agi" 4uotes on% the risk is re'u"e'. Con#enien"e o >or inserting 'ata into a 'ata&ase% !agi" 4uotes essentiall runs a##slas1es23 on all Aet% 9ost% an' Cookie 'ata% an' 'oes so auto!agi"all . @1. not to $se Magic =$otes 9orta&ilit o Assu!ing it to &e on% or o$$% a$$e"ts ,orta&ilit . +se get;&agic;D$otes;gpc23 to "he"k $or this% an' "o'e a""or'ingl . 9er$or!an"e o Ce"ause not e#er ,ie"e o$ es"a,e' 'ata is inserte' into a 'ata&ase% there is a ,er$or!an"e loss $or es"a,ing all this 'ata. Si!,l "alling on the es"a,ing $un"tions 1like a##slas1es232 at runti!e is !ore e$$i"ient. o Although ,h,.ini@'ist ena&les these 'ire"ti#es & 'e$ault% ,h,.ini@ re"o!!en'e' 'isa&les it. .his re"o!!en'ation is !ainl 'ue to ,er$or!an"e reasons. ;n"on#enien"e o Ce"ause not all 'ata nee's es"a,ing% it-s o$ten anno ing to see es"a,e' 'ata *here it shoul'n-t &e. >or exa!,le% e!ailing $ro! a $or!% an' seeing a &un"h o$ [- *ithin the e!ail. .o $ix% this !a re4uire ex"essi#e use o$ stripslas1es23. Disa(ling Magic =$otes .he !agi"P4uotesPg," 'ire"ti#e !a onl &e 'isa&le' at the s ste! le#el% an' not at runti!e. ;n other*or's% use o$ ini;set23 is not an o,tion. 136 Sree Sakthi Engineering College

"i#ing P"P A $e* si!,le te"hni4ues "an hel, to hi'e 9:9% ,ossi&l slo*ing 'o*n an atta"ker *ho is atte!,ting to 'is"o#er *eaknesses in our s ste!. C setting ex,oseP,h, O o$$ in our ,h,.ini $ile% ou re'u"e the a!ount o$ in$or!ation a#aila&le to the!. Another ta"ti" is to "on$igure *e& ser#ers su"h as a,a"he to ,arse 'i$$erent $ilet ,es through 9:9% either *ith an .hta""ess 'ire"ti#e% or in the a,a"he "on$iguration $ile itsel$. Rou "an then use !islea'ing $ile extensions/ E,a&ple 3+:! "i#ing P"P as anot1er lang$age K 7ake 9:9 "o'e look like other "o'e t ,es A''. ,e a,,li"ationDx@htt,'@,h, .as, ., .,l Eeeping C$rrent 9:9% like an other large s ste!% is un'er "onstant s"rutin an' i!,ro#e!ent. Ea"h ne* #ersion *ill o$ten in"lu'e &oth !a)or an' !inor "hanges to enhan"e se"urit an' re,air an $la*s% "on$iguration !isha,s% an' other issues that *ill a$$e"t the o#erall se"urit an' sta&ilit o$ our s ste!.

3 !9 Te&plates: .e!,lating is an eas *a to "reate large sites *ithout !u"h trou&le in !aintaining a "onsistent look an' $eel a"ross the!.;n its si!,lest $or!% a te!,late is an outline $or a *e&site. ;t "ontains all the la out an' ,erha,s so!e CSS $or that ,ur,ose. >or the ,ur,ose o$ this tutorial% *e *ill &e using a si!,le ht!l la out *ith a si'e&ar !enu an' a hea'er an' a !ain "ontent se"tion. .his is 4uite a "o!!on la out an' *e *ill &e !aking the !ain "ontent ' na!i"% so that & "li"king a link in the !enu% the !ain "ontent *ill &e "hange' & in"lu'ing a se,erate ,h, $ile. 137 Sree Sakthi Engineering College

$.13.1 Si-p"e !>! Te-p"ate C"ass -%e used s%o s %o to implement a simple class to %andle page templates. The C"ass Rte-p"ate.c"ass.phpD
NO /lass +em late P u1li/ Qtem lateR Gun/tion load(QGile ath) P Qthis->tem late = Gile<get</ontents(QGile ath)R V Gun/tion re la/e(Qvar? Q/ontent) P Qthis->tem late = str<re la/e(S[Qvar[S? Q/ontent? Qthis->tem late)R V Gun/tion V V O> u1lish() P eval(SO>S-Qthis->tem late-SNOS)R

$.13.# The Te-p"ate Fi"e Rdesi(n.ht-"D -%is file ill contain t%e design of your e( site and t%e (lan+ fields t%at ill (e merged it% content data. T%tmlP T%eadP TtitlePStitleSTCtitleP TC%eadP T(odyP T%=PJello SnameSbTC%=P TpP-%e time is: SdatetimeSTCpP TA ec%o 3TpP@m(edded #J# or+s toobTCpP3K AP
138 Sree Sakthi Engineering College

TC(odyP TC%tmlP Usa(e Rinde=.phpD No


NO in/lude Stem late-/lass- h SR Qtem late = new +em lateR Qtem late->load(Sdesign-htmlS)R Qtem late->re la/e(StitleS? S>C +em late 6lassS)R Qtem late->re la/e(SnameS? SLilliamS)R Qtem late->re la/e(SdatetimeS? Qtem late-> u1lish()R O>

e ill create a script t%at load t%e template and use t%e class to merge t%e data.

date13mCdCy32)R

5%en you run t%e a(ove script* inde'.p%p* it ill output t%e follo ing: T%tmlP T%eadP TtitleP"y -emplate $lassTCtitleP TC%eadP T(odyP T%=PJello 5illiambTC%=P TpP-%e time is: :=C6:C:>TCpP TpP@m(edded #J# or+s toobTCpP TC(odyP TC%tmlP

139 Sree Sakthi Engineering College

UNIT IK

!9T>ON

S)nta= and St)"e W !)thon ObCects W Nu-bers W Se;uences W Strin(s W 2ists and Tup"es W Dictionaries W Conditiona"s and 2oops W Fi"es W Input and Output W 0rrors and 0=ceptions W Functions W 4odu"es W C"asses and OO! W 0=ecution 0n%iron-ent. Introduction@ #yt%on is a general purpose interpreted* interactive* o(4ect)oriented and %ig%)level programming language. #yt%on 1G#L2.#yt%on languages.
140 Sree Sakthi Engineering College

as created (y Guido van Gossum in t%e late eig%ties and early availa(le under t%e GNU General #u(lic License %ic% uses @nglis% +ey ords fre,uently

nineties. Li+e #erl* #yt%on source code is no

as designed to (e %ig%ly reada(le

%ere as ot%er languages use punctuation and it %as fe er syntactical constructions t%an ot%er

!)thon is Interpreted@ -%is means t%at it is processed at runtime (y t%e interpreter and you do not need to compile your program (efore e'ecuting it. -%is is similar to #@GL and #J#.

!)thon is Interacti%e@ -%is means t%at you can actually sit at a #yt%on prompt and interact it% t%e interpreter directly to rite your programs. !)thon is ObCect8Oriented@ -%is means t%at #yt%on supports O(4ect)Oriented style or tec%ni,ue of programming t%at encapsulates code it%in o(4ects. !)thon is 5e(inner+s 2an(ua(e@ #yt%on is a great language for t%e (eginner programmers and supports t%e development of a te't processing to 555 (ro sers to games. ide range of applications* from simple

'.1 S)nta= and St)"e '.1.1 State-ents and S)nta= Some rules and certain sym(ols are used it% regard to statements in #yt%on: S)-bo" Jas% mar+ 1 S 2 N@5LIN@ 1 Zn 2 ?ac+slas% 1 Z 2 Semicolon 1 K 2 $olon 1 : 2 Co--ents@ A %as% sign 1S2 t%at is not inside a string literal (egins a comment. All c%aracters after t%e S and up to t%e p%ysical line end are part of t%e comment* and t%e #yt%on interpreter ignores t%em. SbCusrC(inCpyt%on S /irst comment print 3Jello* #yt%onb3K S second comment -%is ill produce follo ing result:
141 Sree Sakthi Engineering College

Description Indicates #yt%on comments -%e standard line separator 1one statement per line2 $ontinues a line Loins t o statements on a line Separates a %eader line from its suite

Jello* #yt%onb A comment may (e on t%e same line after a statement or e'pression: name V 3"adisetti3 S -%is is again comment 8ou can comment multiple lines as follo s: S -%is is a comment. S -%is is a comment* too. S -%is is a comment* too. S I said t%at already. Continuation R P D@ In #yt%on you normally %ave one instruction per line. Long instructions can span several lines using t%e line)continuation c%aracter XZF. Some instructions* as triple ,uoted strings* list* tuple and dictionary constructors or statements grouped (y parent%eses do not need a line) continuation c%aracter. It is possi(le to are separated (y semi)colons. S c%ec+ conditions if 1 eat%erYisY%ot VV 62 and Z 1s%ar+Y arnings VV :2 : sendYgotoY(eac%YmesgYtoYpager12 4u"tip"e State-ent .roups as Suites R @ D Groups of individual statements ma+ing up a single code (loc+ are called 3suites3 in #yt%on.$ompound or comple' statements* suc% as if* %ile* def* and class* are t%ose %ic% re,uire a %eader line and a suite. Jeader lines (egin t%e statement 1 it% t%e +ey ord2 and terminate it% a colon 1 : 2 and are follo ed (y one or more lines %ic% ma+e up t%e suite. 4u"tip"e State-ents on a Sin("e 2ine R J D -%e semicolon 1 K 2 allo s multiple statements on t%e single line given t%at neit%er statement starts a ne code (loc+. Jere is a sample snip using t%e semicolon:
142 Sree Sakthi Engineering College

rite several statements on t%e same line* provided t%ey

@'ample: import sysK ' V 0foo0K sys.stdout. rite1' I 0Zn02 4odu"e@ A module allo s you to logically organi.e your #yt%on code. Grouping related code into a module ma+es t%e code easier to understand and use. A module is a #yt%on o(4ect it% ar(itrarily named attri(utes t%at you can (ind and reference.Simply* a module is a file consisting of #yt%on code. A module can define functions* classes* and varia(les. A module can also include runna(le code. '.1.# Kariab"e *ssi(n-ent #yt%on varia(les do not %ave to (e e'plicitly declared to reserve memory space. -%e declaration %appens automatically used to assign values to varia(les. -%e operand to t%e left of t%e V operator is t%e name of t%e varia(le* and t%e operand to t%e rig%t of t%e V operator is t%e value stored in t%e varia(le. /or e'ample: SbCusrC(inCpyt%on counter V 6:: miles V 6:::.: name V 3Lo%n3 S An integer assignment S A floating point S A string %en you assign a value to a varia(le. -%e e,ual sign 1V2 is

print counter print miles print name Jere 6::* 6:::.: and 3Lo%n3 are t%e values assigned to counter* miles and name varia(les* respectively. 5%ile running t%is program* t%is ill produce follo ing result: 6:: 6:::.:
143 Sree Sakthi Engineering College

Lo%n 4u"tip"e *ssi(n-ent PPP ' V y V . V 6 PPP ' 6 PPP y 6 PPP . 6 In t%e a(ove e'ample* an integer o(4ect 1 it% t%e value 62 is created* and '* y* and . are all assigned t%e same reference to t%at o(4ect. 4u"tup"e *ssi(n-ent PPP '* y* . V 6* 7* 0a string0 PPP ' 6 PPP y 7 PPP . 0a string0 In t%e a(ove e'ample* t o integer o(4ects 1 it% values 6 and 72 and one string o(4ect are assigned to '* y* and . respectively. '.1.$ Identifiers identifier ::V 1letter_3Y32 1letter _ digit _ 3Y32W letter ::V lo ercase _ uppercase
144 Sree Sakthi Engineering College

lo ercase ::V 3a3...3.3 uppercase ::V 3A3...3\3 digit ::V 3:3...3D3 stringliteral ::V Qstringprefi'R1s%ortstring _ longstring2 stringprefi' ::V 3r3 _ 3u3 _ 3ur3 _ 3G3 _ 3U3 _ 3UG3 _ 3Ur3 _ 3uG3 Be)words -%e follo ing identifiers are used as reserved ords* or keywords of t%e language* and cannot (e used as ordinary identifiers. -%ey must (e spelled e'actly as ritten %ere: and as assert (rea+ class continue def del elif else e'cept e'ec finally for from glo(al if import in is lam(da not or pass print raise return try %ile it% yield

'.1.' 4e-or) 4ana(e-ent


145 Sree Sakthi Engineering College

"emory management in #yt%on involves a private %eap containing all #yt%on o(4ects and data structures. -%e management of t%is private %eap is ensured internally (y t%e Python memory manager. -%e #yt%on memory manager %as different components D)na-ic T)pin( In #yt%on* t%e type and memory space for an o(4ect are determined and allocated at run) time. Alt%oug% code is (yte)compiled* #yt%on is still an interpreted language. 4e-or) *""ocation .arba(e Co""ection 1.C2 is a form of automatic memory management. It is a special case of resource management* in %ic% t%e limited resource (eing managed is memory. -%e gar(age collector* or 4ust collector* attempts to reclaim gar(age* or memory occupied (y o(4ects t%at are no longer in use (y t%e program. #yt%on0s gar(age collector needed* all decide ill automatically deallocate a data o(4ect once is it no longer does #yt%on it%out re,uiring any management on t%e programmer0s part. Jo %ic% deal it% various dynamic storage management aspects* li+e s%aring* segmentation* pre allocation or cac%ing.

%en an o(4ect is 3no longer neededA3 ?y +eeping trac+ of t%e num(er of references to Reference Countin( is a tec%ni,ue of storing t%e num(er of references* pointers* or

o(4ects. -%is is called reference counting. %andles to a resource suc% as an o(4ect* (loc+ of memory* dis+ space or ot%er resource. It may also refer* more specifically* to a gar(age collection algorit%m t%at uses t%ese reference counts to deallocate o(4ects %ic% are no longer referenced '.# !)thon ObCects An o(4ect is a discrete (undle of functions and procedures* often relating to a particular real) orld concept suc% as a (an+ account %older* a %oc+ey player* or a (ulldo.er. '.#.1 !)thon ObCects All #yt%on o(4ects %ave t%is:
o o o

a uni,ue identity 1an integer* returned (y id(x)2 a type 1returned (y type(x)2 some content
146 Sree Sakthi Engineering College

It cannot c%ange t%e identity. It cannot c%ange t%e type. Some o(4ects allo t%eir content 1more (elo 2. O(4ects may also %ave t%is: o o .ero or more met%ods 1provided (y t%e type o(4ect2 .ero or more names

you to c%ange t%eir you to c%ange

content 1 it%out c%anging t%e identity or t%e type* i.e2. Some o(4ects donMt allo

Some o(4ects %ave met%ods t%at allo

you to c%ange t%e contents of t%e o(4ect 1modify it in you to access t%e contents* not c%ange

place* t%at is2.Some o(4ects only %ave met%ods t%at allo it. Some o(4ects donMt %ave any met%ods at all.

@ven if t%ey %ave met%ods* you can never c%ange t%e type* nor t%e identity.-%ings li+e attri(ute assignment and item references are 4ust syntactic sugar 1more (elo 2. '.#.# Standard T)pes Num(ers 1four separate su()types2 Gegular or 3#lain3 Integer Long Integer /loating #oint Geal Num(er $omple' Num(er String List -uple &ictionary '.#.$ Other 5ui"t8in T)pes -ype None /ile /unction "odule $lass $lass Instance
147 Sree Sakthi Engineering College

"et%od -%ese are some of t%e ot%er types you ill interact it% as a #yt%on programmer. T)pes and the t)peRD 5ui"t8in Function Synta' type1o(4ect2 &escription -%e type12 (uilt)in function ta+es o(4ect and returns its type. -%e return o(4ect is a type o(4ect. @'ample PPP type1>2 Sint type Ttype 0int0P PPP PPP type10Jello 5orldb02 Sstring type Ttype 0string0P PPP PPP type1type1>22 Stype type Ttype 0type0P type can ta+e a varia(le and return its datatype. type also or+s on modules. 8ou can use t%e constants in t%e types module to compare types of o(4ects.

'.#.' Interna" T)pes -%e internal -ypes are $ode /rame -race(ac+ Slice @llipsis
148 Sree Sakthi Engineering College

Xrange Code $ode o(4ects are used (y t%e implementation to represent ccpseudo)compiled00 e'ecuta(le #yt%on code suc% as a function (ody. -%ey differ from function o(4ects (ecause t%ey don0t contain a reference to t%eir glo(al e'ecution environment. $ode o(4ects are returned (y t%e (uilt) in /om ile() function and can (e e'tracted from function o(4ects t%roug% t%eir Gun/</ode attri(ute. A code o(4ect can (e e'ecuted or evaluated (y passing it 1instead of a source string2 to t%e e2e/ statement or t%e (uilt)in eval() function. Fra-e -%ese are o(4ects representing e'ecution stac+ frames in #yt%on. /rame o(4ects contain all t%e information t%e #yt%on interpreter needs to +no during a runtime e'ecution environment. Some of its attri(utes include a lin+ to t%e previous stac+ frame* t%e code o(4ect 1see a(ove2 t%at is (eing e'ecuted* dictionaries for t%e local and glo(al namespaces* and t%e current instruction. @ac% function call results in a ne frame o(4ect* and for eac% frame o(4ect* a $ stac+ frame is created as ell. Tracebac& 5%en you ma+e an error in #yt%on* an e'ception is raised. If e'ceptions are not caug%t or 3%andled*3 t%e interpreter e'its it% some diagnostic information similar to t%e output s%o n (elo : -race(ac+ 1innermost last2: /ile 3TstdinP3* line NA* in AAA @rrorName: error reason -%e trace(ac+ o(4ect is 4ust a data item t%at %olds t%e stac+ trace information for an e'ception and is created %en an e'ception occurs. If a %andler is provided for an e'ception* t%is %andler is given access to t%e trace(ac+ o(4ect.

149 Sree Sakthi Engineering College

S"ice ObCects Slice o(4ects are used to represent slices %en e'tended slice synta' is used. -%is is a slice using t o colons* or multiple slices or ellipses separated (y commas* e.g.* aWi:5:ste X* aWi:5? 0:lX* or aW---? i:5X. -%ey are also created (y t%e (uilt)in slice function. Special read)only attri(utes:
o o o

start is t%e lo er (ound stop is t%e upper (ound step is t%e step value

@ac% is of t%e a(ove is None if omitted. -%ese attri(utes can %ave any type. Slice o(4ects support one met%od: indices1self* lengt%2 -%is met%od ta+es a single integer argument lengt% and computes information a(out t%e e'tended slice t%at t%e slice o(4ect ould descri(e if applied to a se,uence of lengt% items. It returns a tuple of t%ree integersK respectively t%ese are t%e start and stop indices and t%e step or stride lengt% of t%e slice. "issing or out)of)(ounds indices are %andled in a manner consistent it% regular slices. 0""ipsis @llipsis is an o(4ect t%at can appear in slice notation. /or e'ample: myListQ6:7* ...* :R Its interpretation is purely up to %atever implements t%e <<getitem<< function and sees $lli sis o(4ects t%ere* (ut its main 1and intended2 use in in t%e numeric pyt%on e'tension* %ic% adds a multidementional array type. Since t%ere are more t%an one dimensions* slicing (ecomes more comple' t%an 4ust a start and stop inde'K it is useful to (e a(le to slice in multiple dimentions as ell. eg* given a >'> array* t%e top left area ould (e defined (y t%e slice 3Q:7*:7R3 PPP a array1Q Q 6* 7* =* > R*
150 Sree Sakthi Engineering College

Q <* B* E* 9 R* Q D* 6:* 66* 67R* Q6=* 6>* 6<* 6BR R2 PPP aQ:7*:7R S top left array1QQ6* 7R* Q<* BRR2 @'tending t%is furt%er* @llipsis is used %ere to indicate a place%older for t%e rest of t%e array dimensions not specified. -%in+ of it as indicating t%e full slice Q:R for all t%e dimentions in t%e gap it is placed* so for a =d array* aW---?0X is t%e same as aW:?:?0X and for >d* aW:?:?:?0X. Similarly aW0?---?0X is aW0?:?:?0X 1 it% %o ever many colons in t%e middle ma+e up t%e full num(er of dimensions in t%e array2. Aran(e XGange o(4ects are created (y t%e (uilt)in function xrange12% a si(ling of t%e range12 (uilt)in function and used %en memory is limited and for %en range12 generates an unusually large data set. '.#., Standard T)pe Operators Co-parison Operators@ $omparison operations may (e applied to any o(4ect. $omparison operations receive %ig%er priority t%an ?oolean operations. $omparisons can (e c%ained in series: 3' T y TV .3 is e,uivalent to 3' T y3 and 3y TV .3 e'cept t%at 3y3 is evaluated only once. If 3' T y3 proves false* 3.3 is not evaluated at all. -%e comparison operations may (e summarised as follo s: Assume varia(le a %olds 6: and varia(le ( %olds 7: t%en: Operator Description $%ec+s if t%e value of t o operands are VV e,ual or not* if yes t%en condition 1a VV (2 is not true. (ecomes true.
151 Sree Sakthi Engineering College

0=a-p"e

$%ec+s if t%e value of t o operands are bV e,ual or not* if values are not e,ual t%en 1a bV (2 is true. condition (ecomes true. $%ec+s if t%e value of t o operands are TP e,ual or not* if values are not e,ual t%en condition (ecomes true. $%ec+s if t%e value of left operand is P greater t%an t%e value of rig%t operand* if 1a P (2 is not true. yes t%en condition (ecomes true. $%ec+s if t%e value of left operand is less T t%an t%e value of rig%t operand* if yes 1a T (2 is true. t%en condition (ecomes true. $%ec+s if t%e value of left operand is PV greater t%an or e,ual to t%e value of rig%t operand* if yes t%en condition (ecomes true. $%ec+s if t%e value of left operand is less TV t%an or e,ual to t%e value of rig%t operand* if yes t%en condition (ecomes true. $omparisons (et een o(4ects of different types* e'cept different numeric types and different string types* never return 3e,ual3. Some types 1e.g.* file o(4ects2 support only a degenerate notion of comparison %ere any t o o(4ects of t%at type are non)e,ual )) e,uality can only (e esta(lis%ed (y comparing t%e contents. -%e X* XQ* U and UQ operators raise a -ype@rror %en an operand is a comple' num(er. Instances of a class usually compare as non)e,ual unless t%e class defines t%e EEc-pEERD met%od. Implementation note: O(4ects of different types 1e'cept num(ers2 are ordered (y t%eir
152 Sree Sakthi Engineering College

1a TP (2 is true. -%is is similar to bV operator.

1a PV (2 is not true.

1a TV (2 is true.

type names. O(4ects of t%e same type t%at don0t support proper comparison are ordered (y t%eir address in memory 1GA"2. - o more comparison operations* 3in3 and 3not in3* are granted t%e same syntactic priority (ut are supported only (y se,uence types. '.#./ Standard T)pe 5ui"t8in Functions c-pRD -%is function compares elements of t o tuples. S)nta=@ cmp1tuple6*tuple72 Or cmp1o(46*o(472 !ara-eters@ Jere is t%e detail of parameters:

tup"e1: first tuple to (e compared tup"e#: second tuple to (e compared

Return Ka"ue@ If elements are of t%e same type* perform t%e compare and return t%e result. If elements are different types* c%ec+ to see if t%ey are num(ers.

If num(ers* perform numeric coercion if necessary and compare. If eit%er element is a num(er* t%en t%e ot%er element is 3larger3 1num(ers are 3smallest32. Ot%er ise* types are sorted alp%a(etically (y name. e e'%aust (ot% tuples

If

e reac%ed t%e end of one of t%e tuples* t%e longer tuple is 3larger.3 If

and s%are t%e same data* t%e result is a tie* meaning t%at : is returned. 0=a-p"e@ SbCusrC(inCpyt%on tuple6* tuple7 V 167=* 0'y.02* 1><B* 0a(c02
153 Sree Sakthi Engineering College

print cmp1tuple6* tuple72K print cmp1tuple7* tuple62K tuple= V tuple7 I 1E9B*2K print cmp1tuple7* tuple=2 -%is ill produce follo ing result: )6 6 )6 strRD and reprRD Geturn a string containing a nicely printa(le representation of an o(4ect. /or strings* t%is returns t%e string itself. -%e difference it% re r(o15e/t) is t%at str(o15e/t) does not al ays attempt to return a string t%at is accepta(le to eval()K its goal is to return a printa(le string. If no argument is given* returns t%e empty string* @@. -%e str function coerces data into a string. @very datatype can (e coerced into a string. str162 %orsemen V Q0 ar0* 0pestilence0* 0famine0R print %orsemen %orsemen.append10#o er(uilder02 print str1%orsemen2 Standard T)pe Operators and 5ui"t8In Functions ?uilt)In /unctions /unction $mp1p(46*o(472 repr1ob 2 str1ob 2 type1ob 2 ]alue $omparisons &escription compares t o o(4ects string representation string representation determines o(4ect type Gesult integer string String type o(4ect
154 Sree Sakthi Engineering College

Operator T P TV PV VV bV TP O(4ect $omparisons /unction is is not ?oolean operators /unction not And or '.#.1 Unsupported T)pes

&escription less t%an greater t%an less t%an or e,ual to greater t%an or e,ual to e,ual to not e,ual to not e,ual to &escription t%e same as not t%e same as

Gesult ?oolean ?oolean ?oolean ?oolean ?oolean ?oolean ?oolean Gesult ?oolean ?oolean

&escription logical negation logical con4uction logical dis4unction

Gesult ?oolean ?oolean ?oolean

A list of types t%at are not supported (y #yt%on. 5oo"ean Unli+e #ascal or Lava* #yt%on does not feature t%e ?oolean type. Use integers instead. char or b)te #yt%on does not %ave a c%ar or (yte type to %old eit%er single c%aracter or 9)(it integers. Use strings of lengt% one for c%aracters and integers for 9)(it num(ers. pointer Since #yt%on manages memory for you* t%ere is no need to access pointer addresses. -%e closest to an address t%at you can get in #yt%on is (y loo+ing at an o(4ect0s identity using t%e id12 (uilt)in function. Since you %ave no control over t%is value* it0s a moot point. int %s. short %s. "on( #yt%on0s plain integers are t%e universal 3standard3 integer type* o(viating t%e need for t%ree different integer types* i.e.* $0s int* s%ort* and long. /or t%e record* #yt%on0s
155 Sree Sakthi Engineering College

integers are implemented as $ longs. /or values larger in magnitude t%an regular integers 1usually your system arc%itecture si.e* i.e.* =7)(it2* use #yt%on0s long integer. f"oat %s. doub"e $ %as (ot% a single precision float type and dou(le)precision dou(le type. #yt%on0s float type is actually a $ dou(le. #yt%on does not support a single)precision floating point type (ecause its (enefits are out eig%ed (y t%e over%ead re,uired to support t o types of floating point types. '.$ Nu-bers Num(er data types store numeric values. -%ey are immuta(le data types* are created %en you assign a value to t%em. /or e'ample: var6 V 6 var7 V 6: 8ou can also delete t%e reference to a num(er o(4ect (y using t%e de" statement. -%e synta' of t%e del statement is: del var6Q*var7Q*var=Q....*varNRRRR 8ou can delete a single o(4ect or multiple o(4ects (y using t%e del statement. /or e'ample: del var del varYa* varY( '.$.1 >ow to Create and *ssi(n Nu-bers RNu-ber ObCectsD $reating num(ers is as simple as assigning a value to a varia(le: anInt V 6 6aLong V )DDDDDDDDDDDDDDDDL a/loat V =.6>6<D7B<=<9DED=7=9>B7B>==9=7ED< a$omple' V 6.7= I >.<BL '.$.# >ow to Update Nu-bers 8ou can 3update3 an e'isting num(er (y 1re2assigning a varia(le to anot%er num(er. -%e ne value can (e related to its previous value or to a completely different num(er
156 Sree Sakthi Engineering College

%ic% means

t%at c%anging t%e value of a num(er data type results in a ne ly allocated o(4ect.Num(er o(4ects

altoget%er. anInt V anInt I 6 a/loat V 7.E69796979 '.$.$ >ow to Re-o%e Nu-bers Under normal circumstances* you do not really 3remove3 a num(erK you 4ust stop using itb If you really ant to delete a reference to a num(er o(4ect* 4ust use t%e de" statement 8ou can no longer use t%e varia(le name* once removed* unless you assign it to a ne o(4ectK ot%er ise* you ill cause a Name@rror e'ception to occur. de" anInt de" aLong* a/loat* a$omple' '.$.' T)pes #yt%on supports four different numerical types:
o

int Rsi(ned inte(ersD: often called 4ust integers or ints* are positive or negative num(ers it% no decimal point. "on( R"on( inte(ers D: or longs* are integers of unlimited si.e* follo ed (y an uppercase or lo ercase L.

%ole

ritten li+e integers and ritten it%

f"oat Rf"oatin( point rea" %a"uesD : or floats* represent real num(ers and are notation* it% @ or e indicating t%e po er of 6: 17.<e7 V 7.< ' 6:7 V 7<:2.

a decimal point dividing t%e integer and fractional parts. /loats may also (e in scientific co-p"e= Rco-p"e= nu-bersD : are of t%e form a I (L* %ere a and ( are floats and L 1or

42 represents t%e s,uare root of )6 1 %ic% is an imaginary num(er2. a is t%e real part of t%e num(er* and ( is t%e imaginary part. $omple' num(ers are not used muc% in #yt%on programming. 0=a-p"es@ Jere are some e'amples of num(ers: int 6: 6:: "on( <6D7>=B6L ):'6D=7=L f"oat :.: 6<.7: co-p"e= =.6>4 ><.4
157 Sree Sakthi Engineering College

)E9B :9: ):>D: ):'7B: :'BD


o

:677L :'&@/A?$@$?&A@$?/?A@l <=<B==B7D9>=L ):<7=696E7E=<L )>E7699<7D9<7DL

)76.D =7.=Ie69 )D:. )=7.<>e6:: E:.7)@67

D.=77e)=B4 .9EB4 ).B<><I:L =eI7BL >.<=e)E4

#yt%on allo s you to use a lo ercase L it% an uppercase L.

it% long* (ut it is recommended t%at you use

only an uppercase L to avoid confusion it% t%e num(er 6. #yt%on displays long integers A comple' num(er consists of an ordered pair of real floating point num(ers denoted (y a I (4* %ere a is t%e real part and ( is t%e imaginary part of t%e comple' num(er. '.$., Nu-ber T)pe Con%ersion #yt%on converts num(ers internally in an e'pression containing mi'ed types to a common type for evaluation. ?ut sometimes* you0ll need to coerce a num(er e'plicitly from one type to anot%er to satisfy t%e re,uirements of an operator or function parameter.
o o o o

-ype intR=Dto convert ' to a plain integer. -ype "on(R=D to convert ' to a long integer. -ype f"oatR=D to convert ' to a floating)point num(er. -ype co-p"e=R=D to convert ' to a comple' num(er it% real part ' and imaginary part .ero. -ype co-p"e=R=? )D to convert ' and y to a comple' num(er it% real part ' and imaginary part y. ' and y are numeric e'pressions

'.$./ 5ui"t8in Nu-ber Functions@ '.$./.1 4athe-atica" Functions@ #yt%on includes follo ing functions t%at perform mat%ematical calculations. Function a(s1'2 Returns R description D -%e a(solute value of ': t%e 1positive2 distance (et een ' and .ero.
158 Sree Sakthi Engineering College

ceil1'2 cmp1'* y2 e'p1'2 fa(s1'2 floor1'2 log1'2 log6:1'2 ma'1'6* '7*...2 min1'6* '7*...2 modf1'2 po 1'* y2 round1' Q*nR2 s,rt1'2

-%e ceiling of ': t%e smallest integer not less t%an ' )6 if ' T y* : if ' VV y* or 6 if ' P y -%e e'ponential of ': e' -%e a(solute value of '. -%e floor of ': t%e largest integer not greater t%an ' -%e natural logarit%m of '* for 'P : -%e (ase)6: logarit%m of ' for 'P : . -%e largest of its arguments: t%e value closest to positive infinity -%e smallest of its arguments: t%e value closest to negative infinity -%e fractional and integer parts of ' in a t o)item tuple. ?ot% parts %ave t%e same sign as '. -%e integer part is returned as a float. -%e value of 'WWy. = rounded to n digits from t%e decimal point. #yt%on rounds a ay from .ero as a tie)(rea+er: round1:.<2 is 6.: and round1):.<2 is )6.:. -%e s

'.$./.# Rando- Nu-ber Functions@ Gandom num(ers are used for games* simulations* testing* security* and privacy applications. #yt%on includes follo ing functions t%at are commonly used. Function c%oice1se,2 randrange 1Qstart*R stop Q*stepR2 random12 seed1Q'R2 Returns R description D A random item from a list* tuple* or string. A randomly selected element from range1start* stop* step2 A random float r* suc% t%at : is less t%an or e,ual to r and r is less t%an 6 Sets t%e integer starting value used in generating random num(ers. $all t%is function (efore calling any ot%er random module function. Geturns
159 Sree Sakthi Engineering College

None. s%uffle1lst2 uniform1'* y2 Gandomi.es t%e items of a list in place. Geturns None. A random float r* suc% t%at ' is less t%an or e,ual to r and r is less t%an y

'.$./.$ Tri(ono-etric Functions@ #yt%on includes follo ing functions t%at perform trigonometric calculations. Function acos1'2 asin1'2 atan1'2 atan71y* '2 cos1'2 %ypot1'* y2 sin1'2 tan1'2 degrees1'2 radians1'2 Description Geturn t%e arc cosine of '* in radians. Geturn t%e arc sine of '* in radians. Geturn t%e arc tangent of '* in radians. Geturn atan1y C '2* in radians. Geturn t%e cosine of ' radians. Geturn t%e @uclidean norm* s,rt1'W' I yWy2. Geturn t%e sine of ' radians. Geturn t%e tangent of ' radians. $onverts angle ' from radians to degrees. $onverts angle ' from degrees to radians.

'.$.1 4athe-atica" Constants@ -%e module also defines t o mat%ematical constants: Constant pi e '.' Se;uences '.'.1 Strin(s
160 Sree Sakthi Engineering College

Description -%e mat%ematical constant pi. -%e mat%ematical constant e.

Strings are amongst t%e most popular types in #yt%on. 5e can create t%em simply (y enclosing c%aracters in ,uotes. #yt%on treats single ,uotes t%e same as dou(le ,uotes. $reating strings is as simple as assigning a value to a varia(le. /or e'ample: var6 V 0Jello 5orldb0 var7 V 3#yt%on #rogramming3 '.'.1.1 *ccessin( Ka"ues in Strin(s@ #yt%on does not support a c%aracter typeK t%ese are treated as strings of lengt% one* t%us also considered a su(string. -o access su(strings* use t%e s,uare (rac+ets for slicing along it% t%e inde' or indices to o(tain your su(string: 0=a-p"e@ SbCusrC(inCpyt%on var6 V 0Jello 5orldb0 var7 V 3#yt%on #rogramming3 print 3var6Q:R: 3* var6Q:R print 3var7Q6:<R: 3* var7Q6:<R -%is ill produce follo ing result: var6Q:R: J var7Q6:<R: yt%o '.'.1.# Updatin( Strin(s 8ou can 3update3 an e'isting string (y 1re2assigning a varia(le to anot%er string. -%e ne value can (e related to its previous value or to a completely different string altoget%er. 0=a-p"e@ SbCusrC(inCpyt%on var6 V 0Jello 5orldb0
161 Sree Sakthi Engineering College

print 3Updated String :) 3* var6Q:BR I 0#yt%on0 -%is ill produce follo ing result: Updated String :) Jello #yt%on '.'.1.$ 0scape Characters /ollo ing ta(le is a list of escape or non)printa(le c%aracters t%at can (e represented it% (ac+slas% notation. NOT0@ In a dou(le,uoted string* an escape c%aracter is interpretedK in a single,uoted string* an escape c%aracter is preserved. 5ac&s"ash notation Za Z( Zc' Z$)' Ze Zf Z")Z$)' Zn Znnn Zr Zs Zt Zv Z' Z'nn >e=adeci-a" character :':E :':9 ) ) :'6( :':c ) :':a ) :':d :'7: :':D :':( ) ) Description ?ell or alert ?ac+space $ontrol)' $ontrol)' @scape /ormfeed "eta)$ontrol)' Ne line Octal notation* %ere n is in t%e range :.E $arriage return Space -a( ]ertical ta( $%aracter ' Je'adecimal notation* %ere n is in t%e range :.D* a.f* or
162 Sree Sakthi Engineering College

A./ '.'.1.' Strin( Specia" Operators Assume string varia(le a %olds 0Jello0 and varia(le ( %olds 0#yt%on0 t%en: Operator Description I $oncatenation ) Adds values on eit%er side of t%e operator Gepetition W string QR Slice ) Gives t%e c%aracter from t%e given inde' Gange Slice ) Gives t%e c%aracters from t%e given range "em(ers%ip ) Geturns true if a c%aracter e'ists in t%e given string "em(ers%ip ) Geturns true if a c%aracter does not e'ist in t%e given string Ga String ) Suppress actual meaning of aQ6R ill give e ) $reates ne strings* 0=a-p"e a I ( ill give Jello#yt%on

concatenating multiple copies of t%e same aW7 ill give )JelloJello

Q:R

aQ6:>R ill give e""

in

> in a ill give 6

not in

4 not in a ill give 6

@scape c%aracters. -%e synta' for ra strings is e'actly t%e same as for normal strings rCG it% t%e e'ception of t%e ra %ic% string operator* t%e letter 3r*3 print r+Pn+ prints Zn and print R+Pn+ prints Zn

precedes t%e ,uotation mar+s. -%e 3r3 can (e lo ercase 1r2 or uppercase 1G2 and must (e placed immediately preceding t%e first ,uote mar+.

163 Sree Sakthi Engineering College

/ormat ) #erforms String formatting

See at ne't section

'.'.1., Strin( For-attin( Operator@ One of #yt%on0s coolest features is t%e string format operator V. -%is operator is uni,ue to strings and ma+es up for t%e pac+ of %aving functions from $0s printf12 family. 0=a-p"e@ SbCusrC(inCpyt%on print 3"y name is ;s and eig%t is ;d +gb3 ; 10\ara0* 762 -%is ill produce follo ing result: "y name is \ara and eig%t is 76 +gb Jere is t%e list of complete set of sym(ols %ic% can (e used along it% ;: For-at S)-bo" ;c ;s ;i ;d ;u ;o ;' ;X ;e ;@ ;f Con%ersion c%aracter string conversion via str12 prior to formatting signed decimal integer signed decimal integer unsigned decimal integer octal integer %e'adecimal integer 1lo ercase letters2 %e'adecimal integer 1U##@Gcase letters2 e'ponential notation 1 it% lo ercase 0e02 e'ponential notation 1 it% U##@Gcase 0@02 floating point real num(er
164 Sree Sakthi Engineering College

;g ;G

t%e s%orter of ;f and ;e t%e s%orter of ;f and ;@

Ot%er supported sym(ols and functionality are listed in t%e follo ing ta(le: S)-bo" W ) I TspP S : ; 1var2 m.n. Functiona"it) argument specifies idt% or precision left 4ustification display t%e sign leave a (lan+ space (efore a positive num(er add t%e octal leading .ero 1 0:0 2 or %e'adecimal leading 0:'0 or 0:X0* depending on %et%er 0'0 or 0X0 ere used. pad from left it% .eros 1instead of spaces2 0;;0 leaves you it% a single literal 0;0 mapping varia(le 1dictionary arguments2 m is t%e minimum total idt% and n is t%e num(er of digits to

display after t%e decimal point 1if appl.2

'.'.1./ Trip"e Nuotes@ #yt%on0s triple ,uotes comes to t%e rescue (y allo ing strings to span multiple lines* including ver(atim N@5LIN@s* -A?s* and any ot%er special c%aracters. -%e synta' for triple ,uotes consists of t%ree consecutive sin("e or doub"e ,uotes. SbCusrC(inCpyt%on paraYstr V 333t%is is a long string t%at is made up of several lines and non)printa(le c%aracters suc% as -A? 1 Zt 2 and t%ey ill s%o up t%at ay %en displayed. N@5LIN@s it%in t%e string* %et%er e'plicitly given li+e t%is it%in t%e (rac+ets Q Zn R* or 4ust a N@5LIN@ it%in
165 Sree Sakthi Engineering College

t%e varia(le assignment ill also s%o up. 333 print paraYstrK -%is ill produce follo ing result. Note %o every single special c%aracter %as (een converted it% an e'plicit carriage return

to its printed form* rig%t do n to t%e last N@5LIN@ at t%e end of t%e string (et een t%e 3up.3 and closing triple ,uotes. Also note t%at N@5LIN@s occur eit%er at t%e end of a line or its escape code 1Zn2: t%is is a long string t%at is made up of several lines and non)printa(le c%aracters suc% as -A? 1 2 and t%ey ill s%o up t%at ay %en displayed. N@5LIN@s it%in t%e string* %et%er e'plicitly given li+e t%is it%in t%e (rac+ets Q R* or 4ust a N@5LIN@ it%in t%e varia(le assignment ill also s%o up. '.'.1.1Raw Strin( Ga strings don0t treat t%e (ac+slas% as a special c%aracter at all. @very c%aracter you put into a ra string stays t%e ay you rote it: SbCusrC(inCpyt%on print 0$:ZZno %ere0 -%is ould print follo ing result: $:Zno %ere No let0s ma+e use of ra string. 5e ould put e'pression in r+e=pression+ as follo s: SbCusrC(inCpyt%on print r0$:ZZno %ere0 -%is ould print follo ing result: $:ZZno %ere
166 Sree Sakthi Engineering College

'.'.1.3 Unicode Strin( Normal strings in #yt%on are stored internally as 9)(it AS$II* c%aracters from most languages in t%e follo ing: SbCusrC(inCpyt%on print u0Jello* orldb0 -%is ould print follo ing result: Jello* orldb As you can see* Unicode strings use t%e prefi' u* 4ust as ra strings use t%e prefi' r. '.'.1.6 5ui"t8in Strin( 4ethods #yt%on includes follo ing string met%od: SN 6 capitali.e12 $apitali.es first letter of string center1 idt%* fillc%ar2 Geturns a space)padded string it% t%e original string centered to a total of idt% columns count1str* (egV :*endVlen1string22 = $ounts %o many times str occurs in string* or in a su(string of string if starting inde' (eg and ending inde' end are given decode1encodingV0U-/)90*errorsV0strict02 = &ecodes t%e string using t%e codec registered for encoding. encoding defaults to t%e default string encoding. encode1encodingV0U-/)90*errorsV0strict02 > Geturns encoded string version of stringK on error* default is to raise a ]alue@rror unless errors is given it% 0ignore0 or 0replace0.
167 Sree Sakthi Engineering College

%ile Unicode strings are

stored as 6B)(it Unicode. -%is allo s for a more varied set of c%aracters* including special orld. I0ll restrict my treatment of Unicode strings to t%e

4ethods with Description

ends it%1suffi'* (egV:* endVlen1string22 < &etermines if string or a su(string of string 1if starting inde' (eg and ending inde' end are given2 ends it% suffi'K Geturns true if so* and false ot%er ise B e'pandta(s1ta(si.eV92 @'pands ta(s in string to multiple spacesK defaults to 9 spaces per ta( if ta(si.e not provided find1str* (egV: endVlen1string22 E &etermine if str occurs in string* or in a su(string of string if starting inde' (eg and ending inde' end are givenK returns inde' if found and )6 ot%er ise 9 inde'1str* (egV:* endVlen1string22 Same as find12* (ut raises an e'ception if str not found isa6num12 D Geturns true if string %as at least 6 c%aracter and all c%aracters are alp%anumeric and false ot%er ise isalp%a12 6: Geturns true if string %as at least 6 c%aracter and all c%aracters are alp%a(etic and false ot%er ise 66 isdigit12 Geturns true if string contains only digits and false ot%er ise islo er12 67 Geturns true if string %as at least 6 cased c%aracter and all cased c%aracters are in lo ercase and false ot%er ise 6= isnumeric12 Geturns true if a unicode string contains only numeric c%aracters and false ot%er ise isspace12 Geturns true if string contains only %itespace c%aracters and false ot%er ise istitle12 Geturns true if string is properly 3titlecased3 and false ot%er ise
168 Sree Sakthi Engineering College

6>

6<

isupper12 6B Geturns true if string %as at least one cased c%aracter and all cased c%aracters are in uppercase and false ot%er ise 4oin1se,2 6E "erges 1concatenates2 t%e string representations of elements in se,uence se, into a string* it% separator string 69 len1string2 Geturns t%e lengt% of t%e string l4ust1 idt%Q* fillc%arR2 6D Geturns a space)padded string it% t%e original string left)4ustified to a total of idt% columns 7: lo er12 $onverts all uppercase letters in string to lo ercase lstrip12 Gemoves all leading %itespace in string ma+etrans12 Geturns a translation ta(le to (e used in translate function. ma'1str2 Geturns t%e ma' alp%a(etical c%aracter from t%e string str min1str2 Geturns t%e min alp%a(etical c%aracter from t%e string str replace1old* ne Q* ma'R2 Geplaces all occurrences of old in string it% ne * or at most ma' occurrences if ma' given rfind1str* (egV:*endVlen1string22 Same as find12* (ut searc% (ac+ ards in string rinde'1 str* (egV:* endVlen1string22 Same as inde'12* (ut searc% (ac+ ards in string
169 Sree Sakthi Engineering College

76

77

7=

7>

7<

7B

7E

r4ust1 idt%*Q* fillc%arR2 79 Geturns a space)padded string it% t%e original string rig%t)4ustified to a total of idt% columns. 7D rstrip12 Gemoves all trailing %itespace of string split1strV33* numVstring.count1str22 =: Splits string according to delimiter str 1space if not provided2 and returns list of su(stringsK split into at most num su(strings if given splitlines1 numVstring.count10Zn022 =6 Splits string at all 1or num2 N@5LIN@s and returns a list of eac% line it% N@5LIN@s removed starts it%1str* (egV:*endVlen1string22 =7 &etermines if string or a su(string of string 1if starting inde' (eg and ending inde' end are given2 starts it% su(string strK Geturns true if so* and false ot%er ise == strip1Qc%arsR2 #erforms (ot% lstrip12 and rstrip12 on string s apcase12 Inverts case for all letters in string title12 =< Geturns 3titlecased3 version of string* t%at is* all ords (egin it% uppercase* and t%e rest are lo ercase translate1ta(le* deletec%arsV332 =B -ranslates string according to translation ta(le str17<B c%ars2* removing t%ose in t%e del string =E =9 upper12 $onverts lo ercase letters in string to uppercase .fill 1 idt%2
170 Sree Sakthi Engineering College

=>

Geturns original string leftpadded it% .eros to a total of idt% c%aractersK intended for num(ers* .fill12 retains any sign given 1less one .ero2 =D isdecimal12 Geturns true if a unicode string contains only decimal c%aracters and false ot%er ise

'.# 2ists '.#.1 !)thon Se;uences -%e most (asic data structure in #yt%on is t%e se,uence. @ac% element of a se,uence is assigned a num(er ) its position* or inde'. -%e first inde' is .ero* t%e second inde' is one* and so fort%. #yt%on %as si' (uilt)in types of se,uences. -%ere are certain t%ings you can do it% all se,uence types. -%ese operations include inde'ing* slicing* adding* multiplying* and c%ec+ing for mem(ers%ip. In addition* #yt%on %as (uilt)in functions for finding t%e lengt% of a se,uence* and for finding its largest and smallest elements. '.#.# !)thon 2ists -%e list is a most versatile data type availa(le in #yt%on* %ic% can (e ritten as a list of comma)separated values 1items2 (et een s,uare (rac+ets. Good t%ing a(out a list t%at items in a list need not all %ave t%e same type: $reating a list is as simple as putting different comma)separated values (et een s,uere (rac+ets. /or e'ample: list6 V Q0p%ysics0* 0c%emistry0* 6DDE* 7:::RK list7 V Q6* 7* =* >* < RK list= V Q3a3* 3(3* 3c3* 3d3RK Li+e string indices* list indices start at :* and lists can (e sliced* concatenated and so on.
171 Sree Sakthi Engineering College

'.#.$ *ccessin( Ka"ues in 2ists -o access values in lists* use t%e s,uare (rac+ets for slicing along o(tain value availa(le at t%at inde': 0=a-p"e@ SbCusrC(inCpyt%on list6 V Q0p%ysics0* 0c%emistry0* 6DDE* 7:::RK list7 V Q6* 7* =* >* <* B* E RK print 3list6Q:R: 3* list6Q:R print 3list7Q6:<R: 3* list7Q6:<R -%is ill produce follo ing result: list6Q:R: p%ysics list7Q6:<R: Q7* =* >* <R '.#.' Updatin( 2ists 8ou can update single or multiple elements of lists (y giving t%e slice on t%e left)%and side of t%e assignment operator* and you can add to elements in a list it% t%e append12 met%od: 0=a-p"e@ SbCusrC(inCpyt%on list6 V Q0p%ysics0* 0c%emistry0* 6DDE* 7:::RK print 3]alue availa(le at inde' 7 : 3 print list6Q7RK list6Q7R V 7::6K print 3Ne value availa(le at inde' 7 : 3 print list6Q7RK Note@ append12 met%od is discussed in su(se,uent section. -%is ill produce follo ing result:
172 Sree Sakthi Engineering College

it% t%e inde' or indices to

]alue availa(le at inde' 7 : 6DDE Ne value availa(le at inde' 7 : 7::6 '.#., De"ete 2ist 0"e-ents -o remove a list element* you can use eit%er t%e del statement if you +no element1s2 you are deleting or t%e remove12 met%od if you do not +no . 0=a-p"e@ SbCusrC(inCpyt%on list6 V Q0p%ysics0* 0c%emistry0* 6DDE* 7:::RK print list6K del list6Q7RK print 3After deleting value at inde' 7 : 3 print list6K -%is ill produce follo ing result: Q0p%ysics0* 0c%emistry0* 6DDE* 7:::R After deleting value at inde' 7 : Q0p%ysics0* 0c%emistry0* 7:::R Note@ remove12 met%od is discussed in su(se,uent section. '.#./ 5asic 2ist Operations Lists respond to t%e I and W operators muc% li+e stringsK t%ey mean concatenation and repetition %ere too* e'cept t%at t%e result is a ne list* not a string. !)thon 0=pression len1Q6* 7* =R2 Q6* 7* =R I Q>* <* BR Resu"ts = Q6* 7* =* >* <* BR Description Lengt% $oncatenation
173 Sree Sakthi Engineering College

e'actly

%ic%

Q0Jib0R W > = in Q6* 7* =R for ' in Q6* 7* =R: print '*

Q0Jib0* 0Jib0* 0Jib0* 0Jib0R -rue 67=

Gepetition "em(ers%ip Iteration

'.#.1 Inde=in(? S"icin(? and 4atri=es ?ecause lists are se,uences* inde'ing and slicing strings. Assuming follo ing input: L V Q0spam0* 0Spam0* 0S#A"b0R !)thon 0=pression LQ7R LQ)7R LQ6:R Resu"ts 0S#A"b0 0Spam0 Q0Spam0* 0S#A"b0R Description Offsets start at .ero Negative: count from t%e rig%t Slicing fetc%es sections or+ t%e same ay for lists as t%ey do for

'.#.3 5ui"t8in 2ist Functions & 4ethods #yt%on includes follo ing list functions SN Function with Description 6 cmp1list6* $ompares elements of (ot% lists. len1list2 Gives t%e total lengt% of t%e list. ma'1list2 Geturns item from t%e list it% ma' value. min1list2 Geturns item from t%e list it% min value. list72

>

174 Sree Sakthi Engineering College

<

list1se,2 $onverts a tuple into list.

#yt%on includes follo ing list met%ods SN 4ethods with Description 6 list.append1o(42 Appends o(4ect o(4 to list list.count1o(42 Geturns count of %o many times o(4 occurs in list list.e'tend1se,2 Appends t%e contents of se, to list list.inde'1o(42 Geturns t%e lo est inde' in list t%at o(4 appears list.insert1inde'* Inserts o(4ect o(4 into list at offset inde' list.pop1o(4VlistQ)6R2 Gemoves and returns last o(4ect or o(4 from list list.remove1o(42 Gemoves o(4ect o(4 from list list.reverse12 Geverses o(4ects of list in place list.sort1QfuncR2 Sorts o(4ects of list* use compare func if given o(42

>

<

'.$ Tup"es

175 Sree Sakthi Engineering College

A tuple is a se,uence of immuta(le #yt%on o(4ects. -uples are se,uences* 4ust li+e lists. -%e only difference is t%at tuples can0t (e c%anged ie. tuples are immuta(le and tuples use parent%eses and lists use s,uare (rac+ets. $reating a tuple is as simple as putting different comma)separated values and optionally you can put t%ese comma)separated values (et een parent%eses also. /or e'ample: tup6 V 10p%ysics0* 0c%emistry0* 6DDE* 7:::2K tup7 V 16* 7* =* >* < 2K tup= V 3a3* 3(3* 3c3* 3d3K -%e empty tuple is ritten as t o parent%eses containing not%ing: tup6 V 12K -o rite a tuple containing a single value you %ave to include a comma* even t%oug% t%ere is only one value: tup6 V 1<:*2K Li+e string indices* tuple indices start at :* and tuples can (e sliced* concatenated and so on. '.$.1 *ccessin( Ka"ues in Tup"es -o access values in tuple* use t%e s,uare (rac+ets for slicing along indices to o(tain value availa(le at t%at inde': 0=a-p"e@ SbCusrC(inCpyt%on tup6 V 10p%ysics0* 0c%emistry0* 6DDE* 7:::2K tup7 V 16* 7* =* >* <* B* E 2K print 3tup6Q:R: 3* tup6Q:R print 3tup7Q6:<R: 3* tup7Q6:<R -%is ill produce follo ing result: tup6Q:R: p%ysics tup7Q6:<R: Q7* =* >* <R
176 Sree Sakthi Engineering College

it% t%e inde' or

Updatin( Tup"es@ -uples are immuta(le 0=a-p"e@ SbCusrC(inCpyt%on tup6 V 167* =>.<B2K tup7 V 10a(c0* 0'y.02K S /ollo ing action is not valid for tuples S tup6 IV tup7K S So let0s create a ne tuple as follo s tup= V tup6 I tup7K print tup=K -%is ill produce follo ing result: 167* =>.<B* 0a(c0* 0'y.02 '.$.# De"ete Tup"e 0"e-ents Gemoving individual tuple elements is not possi(le. -%ere is* of course* not%ing it% putting toget%er anot%er tuple 0=a-p"e@ SbCusrC(inCpyt%on tup V 10p%ysics0* 0c%emistry0* 6DDE* 7:::2K print tupK del tupK print 3After deleting tup : 3 print tupK
177 Sree Sakthi Engineering College

%ic% means you cannot update t%em or c%ange values of tuple elements.

?ut e a(le a(le to ta+e portions of an e'isting tuples to create a ne tuples as follo s:

rong

it% t%e undesired elements discarded. -o e'plicitly remove

an entire tuple* 4ust use t%e de" statement:

-%is ill produce follo ing result. Note an e'ception raised* t%is is (ecause after de" tup tuple does not e'ist any more: 10p%ysics0* 0c%emistry0* 6DDE* 7:::2 After deleting tup : -race(ac+ 1most recent call last2: /ile 3test.py3* line D* in TmoduleP print tupK Name@rror: name 0tup0 is not defined '.$.$ 5asic Tup"es Operations@ -uples respond to t%e I and W operators muc% li+e stringsK t%ey mean concatenation and repetition %ere too* e'cept t%at t%e result is a ne tuple* not a string. !)thon 0=pression len116* 7* =22 16* 7* =2 I 1>* <* B2 Q0Jib0R W > = in 16* 7* =2 for ' in 16* 7* =2: print '* = 16* 7* =* >* <* B2 10Jib0* 0Jib0* 0Jib0* 0Jib02 -rue 67= Resu"ts Lengt% $oncatenation Gepetition "em(ers%ip Iteration Description

'.$.' Inde=in(? S"icin(? and 4atri=es ?ecause tuples are se,uences* inde'ing and slicing or+ t%e same ay for tuples as t%ey do for strings. Assuming follo ing input: L V 10spam0* 0Spam0* 0S#A"b02 !)thon 0=pression LQ7R LQ)7R 0S#A"b0 0Spam0 Resu"ts Description Offsets start at .ero Negative: count from t%e rig%t
178 Sree Sakthi Engineering College

LQ6:R '.'.' No 0nc"osin( De"i-iters

Q0Spam0* 0S#A"b0R

Slicing fetc%es sections

Any set of multiple o(4ects* comma)separated* ritten it%out identifying sym(ols* i.e.* (rac+ets for lists* parent%eses for tuples* etc.* default to tuples* as indicated in t%ese s%ort e'amples: SbCusrC(inCpyt%on print 0a(c0* )>.7>eD=* 69IB.B4* 0'y.0K '* y V 6* 7K print 3]alue of ' * y : 3* '*yK print varK -%is ill reduce follo ing result: a(c )>.7>eID= 169IB.B42 'y. ]alue of ' * y : 6 7 '.$., 5ui"t8in Tup"e Functions #yt%on includes follo ing tuple functions SN 6 cmp1tuple6* tuple72 $ompares elements of (ot% tuples. len1tuple2 Gives t%e total lengt% of t%e tuple. ma'1tuple2 Geturns item from t%e tuple it% ma' value. min1tuple2 Geturns item from t%e tuple it% min value. tuple1se,2 $onverts a list into tuple.
179 Sree Sakthi Engineering College

Function with Description

>

<

'., Dictionaries A dictionary is muta(le and is anot%er container type t%at can store any num(er of #yt%on o(4ects* including ot%er container types. &ictionaries consist of pairs 1called items2 of +eys and t%eir corresponding values. #yt%on dictionaries are also +no n as associative arrays or %as% ta(les. -%e general synta' of a dictionary is as follo s: dict V ^0Alice0: 07=>60* 0?et%0: 0D6:70* 0$ecil0: 0=7<90` 8ou can create dictionary in t%e follo ing ay as ell: dict6 V ^ 0a(c0: ><B `K dict7 V ^ 0a(c0: 67=* D9.B: =E `K @ac% +ey is separated from its value (y a colon 1:2* t%e items are separated (y commas* and t%e %ole t%ing is enclosed in curly (races. An empty dictionary it%out any items is ritten it% 4ust t o curly (races* li+e t%is: ^`. !eys are uni,ue tuples. '.,.1 *ccessin( Ka"ues in Dictionar) -o access dictionary elements* you use t%e familiar s,uare (rac+ets along o(tain its value: 0=a-p"e@ SbCusrC(inCpyt%on dict V ^0Name0: 0\ara0* 0Age0: E* 0$lass0: 0/irst0`K print 3dictQ0Name0R: 3* dictQ0Name0RK print 3dictQ0Age0R: 3* dictQ0Age0RK -%is ill produce follo ing result: dictQ0Name0R: \ara dictQ0Age0R: E
180 Sree Sakthi Engineering College

it%in a dictionary

%ile values may not (e. -%e values of a dictionary

can (e of any type* (ut t%e +eys must (e of an immuta(le data type suc% as strings* num(ers* or

it% t%e +ey to

If e attempt to access a data item as follo s: SbCusrC(inCpyt%on

it% a +ey %ic% is not part of t%e dictionary*

e get an error

dict V ^0Name0: 0\ara0* 0Age0: E* 0$lass0: 0/irst0`K print 3dictQ0Alice0R: 3* dictQ0Alice0RK -%is ill produce follo ing result: dictQ0\ara0R: -race(ac+ 1most recent call last2: /ile 3test.py3* line >* in TmoduleP print 3dictQ0Alice0R: 3* dictQ0Alice0RK !ey@rror: 0Alice0 '.,.# Updatin( Dictionar) 8ou can update a dictionary (y adding a ne 0=a-p"e@ SbCusrC(inCpyt%on dict V ^0Name0: 0\ara0* 0Age0: E* 0$lass0: 0/irst0`K dictQ0Age0R V 9K S update e'isting entry dictQ0Sc%ool0R V 3&#S Sc%ool3K S Add ne entry Sprint 3dictQ0Age0R: 3* dictQ0Age0RK print 3dictQ0Sc%ool0R: 3* dictQ0Sc%ool0RK -%is ill produce follo ing result: dictQ0Age0R: 9
181 Sree Sakthi Engineering College

entry or item 1i.e.* a +ey)value pair2*

modifying an e'isting entry* or deleting an e'isting entry as s%o n (elo :

dictQ0Sc%ool0R: &#S Sc%ool '.,.$ De"ete Dictionar) 0"e-ents 8ou can eit%er remove individual dictionary elements or clear t%e entire contents of a dictionary. 8ou can also delete entire dictionary in a single operation. -o e'plicitly remove an entire dictionary* 4ust use t%e de" statement: 0=a-p"e@ SbCusrC(inCpyt%on dict V ^0Name0: 0\ara0* 0Age0: E* 0$lass0: 0/irst0`K del dictQ0Name0RK S remove entry it% +ey 0Name0 dict.clear12K del dict K S remove all entries in dict S delete entire dictionary

print 3dictQ0Age0R: 3* dictQ0Age0RK -%is print 3dictQ0Sc%ool0R: 3* dictQ0Sc%ool0RK ill produce follo ing result. Note an e'ception raised* t%is is (ecause after de" dict

dictionary does not e'ist any more: dictQ0Age0R: -race(ac+ 1most recent call last2: /ile 3test.py3* line 9* in TmoduleP print 3dictQ0Age0R: 3* dictQ0Age0RK -ype@rror: 0type0 o(4ect is unsu(scripta(le Note@ del12 met%od is discussed in su(se,uent section. '.,.' !roperties of Dictionar) Be)s &ictionary values %ave no restrictions. -%ey can (e any ar(itrary #yt%on o(4ect* eit%er standard o(4ects or user)defined o(4ects. Jo ever* same is not true for t%e +eys. -%ere are t o important points to remem(er a(out dictionary +eys:
182 Sree Sakthi Engineering College

RaD "ore t%an one entry per +ey not allo ed. 5%ic% means no duplicate +ey is allo ed. 5%en duplicate +eys encountered during assignment* t%e last assignment ins. 0=a-p"e@ SbCusrC(inCpyt%on dict V ^0Name0: 0\ara0* 0Age0: E* 0Name0: 0"anni0`K print 3dictQ0Name0R: 3* dictQ0Name0RK -%is ill produce follo ing result: dictQ0Name0R: "anni RbD !eys must (e immuta(le. 5%ic% means you can use strings* num(ers* or tuples as dictionary +eys (ut somet%ing li+e Q0+ey0R is not allo ed. E ample! SbCusrC(inCpyt%on dict V ^Q0Name0R: 0\ara0* 0Age0: E`K print 3dictQ0Name0R: 3* dictQ0Name0RK -%is ill produce follo ing result. Note an e'ception raised: -race(ac+ 1most recent call last2: /ile 3test.py3* line =* in TmoduleP dict V ^Q0Name0R: 0\ara0* 0Age0: E`K -ype@rror: list o(4ects are un%as%a(le '.,., 5ui"t8in Dictionar) Functions & 4ethods #yt%on includes follo ing dictionary functions SN 6 cmp1dict6* dict72 $ompares elements of (ot% dict.
183 Sree Sakthi Engineering College

Function with Description

len1dict2 7 Gives t%e total lengt% of t%e dictionary. -%is ould (e e,ual to t%e num(er of items in t%e dictionary. = str1dict2 #roduces a printa(le string representation of a dictionary type1varia(le2 > Geturns t%e type of t%e passed varia(le. If passed varia(le is dictionary t%en it ould return a dictionary type. #yt%on includes follo ing dictionary met%ods SN 6 dict.clear12 Gemoves all elements of dictionary dict dict.copy12 Geturns a s%allo copy of dictionary dict dict.from+eys12 $reate a ne dictionary it% +eys from se, and values set to value. dict.get1+ey* defaultVNone2 /or key +ey* returns value or default if +ey not in dictionary dict.%asY+ey1+ey2 Geturns true if +ey in dictionary dict* false ot%er ise dict.items12 Geturns a list of dict0s 1+ey* value2 tuple pairs dict.+eys12 Geturns list of dictionary dict0s +eys dict.setdefault1+ey* defaultVNone2 Similar to get12* (ut ill set dictQ+eyRVdefault if key is not already in dict dict.update1dict72
184 Sree Sakthi Engineering College

4ethods with Description

>

<

E 9

Adds dictionary dict!0s +ey)values pairs to dict D dict.values12 Geturns list of dictionary dict!0s values

'./ Conditiona"s and 2oops $onditional constructs are used to incorporate decision ma+ing into programs. -%e result of t%is decision ma+ing determines t%e se,uence in './.1 The if state-ent -%e if statement of #yt%on is similar to t%at of ot%er languages. -%e if statement contains a logical e'pression using t%e comparison. The s)nta= of the if state-ent is@ if e'pression: statement1s2 Jere if statement* condition is evaluated first. If condition is true t%at is* if its value is non.ero t%en t%e statement1s2 (loc+ are e'ecuted. Ot%er ise* t%e ne't statement follo ing t%e statement1s2 (loc+ is e'ecuted. Note@ In #yt%on* all t%e statements indented (y t%e same num(er of c%aracter spaces after a programming construct are considered to (e part of a single (loc+ of code. #yt%on uses indentation as its met%od of grouping statements. 0=a-p"e@ SbCusrC(inCpyt%on var6 V 6::
185 Sree Sakthi Engineering College

%ic% a program

ill e'ecute instructions.

8ou can control t%e flo of a program (y using conditional constructs.

%ic% data is compared* and a decision is made (ased on t%e result of

if var6: print 36 ) Got a true e'pression value3 print var6 var7 V : if var7: print 37 ) Got a true e'pression value3 print var7 print 3Good (yeb3 -%is ill produce follo ing result: 6 ) Got a true e'pression value 6:: Good (yeb './.# The e"se State-ent An e"se statement can (e com(ined it% an if statement. An e"se statement contains t%e (loc+ of code t%at e'ecutes if t%e conditional e'pression in t%e if statement resolves to : or a false value. -%e else statement is an optional statement and t%ere could (e at most only one e"se statement follo ing if . -%e synta' of t%e if...else statement is: if e'pression: statement1s2 else: statement1s2 0=a-p"e@ SbCusrC(inCpyt%on var6 V 6:: if var6:
186 Sree Sakthi Engineering College

print 36 ) Got a true e'pression value3 print var6 else: print 36 ) Got a false e'pression value3 print var6 var7 V : if var7: print 37 ) Got a true e'pression value3 print var7 else: print 37 ) Got a false e'pression value3 print var7 print 3Good (yeb3 -%is ill produce follo ing result: 6 ) Got a true e'pression value 6:: 7 ) Got a false e'pression value : Good (yeb './.$ The e"if State-ent -%e e"if statement allo s you to c%ec+ multiple e'pressions for trut% value and e'ecute a (loc+ of code as soon as one of t%e conditions evaluates to true. Li+e t%e e"se* t%e e"if statement is optional. Jo ever* unli+e e"se* for -%e synta' of t%e if...elif statement is: if e'pression6: statement1s2
187 Sree Sakthi Engineering College

%ic% t%ere can (e at most one statement* t%ere can (e an

ar(itrary num(er of e"if statements follo ing an if.

elif e'pression7: statement1s2 elif e'pression=: statement1s2 else: statement1s2 Note@ #yt%on does not currently support s itc% or case statements as in ot%er languages. 0=a-p"e@ SbCusrC(inCpyt%on var V 6:: if var VV 7::: print 36 ) Got a true e'pression value3 print var elif var VV 6<:: print 37 ) Got a true e'pression value3 print var7 elif var VV 6::: print 3= ) Got a true e'pression value3 print var else: print 3> ) Got a false e'pression value3 print var print 3Good (yeb3 -%is ill produce follo ing result: = ) Got a true e'pression value 6::
188 Sree Sakthi Engineering College

Good (yeb './.' The Nested if...e"if...e"se Construct -%ere may (e a situation %en you ant to c%ec+ for anot%er condition after a condition resolves to true. In suc% a situation* you can use t%e nested if construct. In a nested if construct* you can %ave an if...e"if...e"se construct inside anot%er if...e"if...e"se construct. -%e synta' of t%e nested if...elif...else construct may (e: if e'pression6: statement1s2 if e'pression7: statement1s2 elif e'pression=: statement1s2 else statement1s2 elif e'pression>: statement1s2 else: statement1s2 0=a-p"e@ SbCusrC(inCpyt%on var V 6:: if var T 7::: print 3@'pression value is less t%an 7::3 if var VV 6<:: print 35%ic% is 6<:3 elif var VV 6::: print 35%ic% is 6::3
189 Sree Sakthi Engineering College

elif var VV <:: print 35%ic% is <:3 elif var T <:: print 3@'pression value is less t%an <:3 else: print 3$ould not find true e'pression3 print 3Good (yeb3 -%is ill produce follo ing result: @'pression value is less t%an 7:: 5%ic% is 6:: Good (yeb './., Sin("e State-ent Suites If t%e suite of an if clause consists only of a single line* it may go on t%e same line as t%e %eader statement: Jere is an e'ample of a one)line if clause: if 1 e'pression VV 6 2 : print 3]alue of e'pression is 63 '././ !)thon 8 whi"e 2oop State-ents A loop is a construct t%at causes a section of a program to (e repeated a certain num(er of times. -%e repetition continues follo ing t%e loop. The whi"e 2oop@ -%e whi"e loop is one of t%e looping constructs availa(le in #yt%on. -%e whi"e loop continues until t%e e'pression (ecomes false. -%e e'pression %as to (e a logical e'pression and must return eit%er a true or a false value. -%e synta' of t%e %ile loop is:
190 Sree Sakthi Engineering College

%ile t%e condition set for t%e loop remains true. 5%en t%e

condition (ecomes false* t%e loop ends and t%e program control is passed to t%e statement

%ile e'pression: statement1s2 Jere e=pression statement is evaluated first. If e'pression is true t%at is* t%en t%e statement1s2 (loc+ is e'ecuted repeatedly until e'pression (ecomes false. Ot%er ise* t%e ne't statement follo ing t%e statement1s2 (loc+ is e'ecuted. Note@ In #yt%on* all t%e statements indented (y t%e same num(er of c%aracter spaces after a programming construct are considered to (e part of a single (loc+ of code. #yt%on uses indentation as its met%od of grouping statements. 0=a-p"e@ SbCusrC(inCpyt%on count V : %ile 1count T D2: print 0-%e count is:0* count count V count I 6 print 3Good (yeb3 -%is ill produce follo ing result: -%e count is: : -%e count is: 6 -%e count is: 7 -%e count is: = -%e count is: > -%e count is: < -%e count is: B -%e count is: E -%e count is: 9 Good (yeb
191 Sree Sakthi Engineering College

-%e (loc+ %ere* consisting of t%e print and increment statements* is e'ecuted repeatedly until count is no longer less t%an D. 5it% eac% iteration* t%e current value of t%e inde' count is displayed and t%en increased (y 6. The Infinite 2oops@ 8ou must use caution %en using %ile loops (ecause of t%e possi(ility t%at t%is %ere t%e %en condition never resolves to a false value. -%is results in a loop t%at never ends. Suc% a loop is called an infinite loop.An infinite loop mig%t (e useful in clientCserver programming server needs to run continuously so t%at client programs can communicate re,uired. 0=a-p"e@ /ollo ing loop ill continue till you enter $-GLI$ : SbCusrC(inCpyt%on var V 6 %ile var VV 6 : S -%is constructs an infinite loop num V ra Yinput13@nter a num(er :32 print 38ou entered: 3* num print 3Good (yeb3 -%is ill produce follo ing result: @nter a num(er :7: 8ou entered: 7: @nter a num(er :7D 8ou entered: 7D @nter a num(er := 8ou entered: = @nter a num(er (et een :-race(ac+ 1most recent call last2: /ile 3test.py3* line <* in TmoduleP
192 Sree Sakthi Engineering College

it% it as and

num V ra Yinput13@nter a num(er :32 !ey(oardInterrupt A(ove e'ample ill go in an infite loop and you ould need to use $-GLI$ to come out of t%e program. Sin("e State-ent Suites@ Similar to t%e if statement synta'* if your whi"e clause consists only of a single statement* it may (e placed on t%e same line as t%e %ile %eader. Jere is t%e synta' of a one)line %ile clause: %ile e'pression : statement './.1 !)thon 8 for 2oop State-ents A loop is a construct t%at causes a section of a program to (e repeated a certain num(er of times. -%e repetition continues follo ing t%e loop. The for 2oop@ -%e for loop in #yt%on %as t%e a(ility to iterate over t%e items of any se,uence* suc% as a list or a string. -%e synta' of t%e loop loo+ is: for iteratingYvar in se,uence: statements1s2 If a se,uence contains an e'pression list* it is evaluated first. -%en* t%e first item in t%e se,uence is assigned to t%e iterating varia(le iteratingYvar. Ne't* t%e statements (loc+ is e'ecuted. @ac% item in t%e list is assigned to iteratingYvar* and t%e statements1s2 (loc+ is e'ecuted until t%e entire se,uence is e'%austed. Note@ In #yt%on* all t%e statements indented (y t%e same num(er of c%aracter spaces after a programming construct are considered to (e part of a single (loc+ of code. #yt%on uses indentation as its met%od of grouping statements. %ile t%e condition set for t%e loop remains true. 5%en t%e condition (ecomes false* t%e loop ends and t%e program control is passed to t%e statement

193 Sree Sakthi Engineering College

0=a-p"e@ SbCusrC(inCpyt%on for letter in +!)thon+@ S /irst @'ample

print 0$urrent Letter :0* letter fruits V Q0(anana0* 0apple0* 0mango0R for fruit in fruits: S Second @'ample print 0$urrent fruit :0* fruit print 3Good (yeb3 -%is ill produce follo ing result: $urrent Letter : # $urrent Letter : y $urrent Letter : t $urrent Letter : % $urrent Letter : o $urrent Letter : n $urrent fruit : (anana $urrent fruit : apple $urrent fruit : mango Good (yeb Iteratin( b) Se;uence Inde=@ An alternative ay of iterating t%roug% eac% item is (y inde' offset into t%e se,uence itself: 0=a-p"e@ SbCusrC(inCpyt%on fruits V Q0(anana0* 0apple0* 0mango0R
194 Sree Sakthi Engineering College

for inde' in range1len1fruits22: print 0$urrent fruit :0* fruitsQinde'R print 3Good (yeb3 -%is ill produce follo ing result: $urrent fruit : (anana $urrent fruit : apple $urrent fruit : mango Good (yeb Jere e too+ t%e assistance of t%e len12 (uilt)in function* elements in t%e tuple as iterate over. %ic% provides t%e total num(er of

ell as t%e range12 (uilt)in function to give us t%e actual se,uence to

'.1 Fi"es and Input:Output '.1.1 !rintin( to the Screen -%e simplest ay to produce output is using t%e print statement %ere you can pass .ero or more e'pressions* separated (y commas. -%is function converts t%e e'pressions you pass it to a string and rites t%e result to standard output as follo s: SbCusrC(inCpyt%on print 3#yt%on is really a great language*3* 3isn0t itA3K -%is ould produce follo ing result on your standard screen: #yt%on is really a great language* isn0t itA '.1.# Readin( Be)board Input #yt%on provides t o (uilt)in functions to read a line of te't from standard input* default comes from t%e +ey(oard. -%ese functions are:

%ic% (y

ra Yinput input
195 Sree Sakthi Engineering College

The rawEinput "unction! -%e raw"input(#prompt$) function reads one line from standard input and returns it as a string 1removing t%e trailing ne line2: SbCusrC(inCpyt%on str V ra Yinput13@nter your input: 32K print 3Geceived input is : 3* str -%is ould prompt you to enter any string and it I typed 3Jello #yt%onb3* it output is li+e t%is: @nter your input: Jello #yt%on Geceived input is : Jello #yt%on The input "unction! -%e input(#prompt$) function is e,uivalent to ra Yinput* e'cept t%at it assumes t%e input is a valid #yt%on e'pression and returns t%e evaluated result to you: SbCusrC(inCpyt%on str V input13@nter your input: 32K print 3Geceived input is : 3* str -%is ould produce follo ing result against t%e entered input: @nter your input: Q'W< for ' in range17*6:*72R Gecieved input is : Q6:* 7:* =:* >:R '.1.$ Openin( and C"osin( Fi"es #yt%on provides (asic functions and met%ods necessary to manipulate files (y default. 8ou can do your most of t%e file manipulation using a fi"e o(4ect. The open Function@ ?efore you can read or associated it% it.
196 Sree Sakthi Engineering College

ould display same string on t%e screen. 5%en

rite a file* you %ave to open it using #yt%on0s (uilt)in open12 function. %ic% ould (e utili.ed to call ot%er support met%ods

-%is function creates a fi"e o(4ect

S)nta=@ file o(4ect V open1fileYname Q* accessYmodeRQ* (ufferingR2 Jere is paramters detail:


o

fi"eEna-e@ -%e fileYname argument is a string value t%at contains t%e name of t%e file t%at you ant to access. accessE-ode@ -%e accessYmode determines t%e mode in ie. read* %ic% t%e file %as to (e opened in t%e ta(le.

rite append etc. A complete list of possi(le values is given (elo

-%is is optional parameter and t%e default file access mode is read 1r2
o

bufferin(@ If t%e (uffering value is set to :* no (uffering value is 6* line (uffering ill (e performed

ill ta+e place. If t%e (uffering ill (e performed it%

%ile accessing a file. If you specify t%e

(uffering value as an integer greater t%an 6* t%en (uffering action (e%avior2. Jere is a list of t%e different modes of opening a file: 4odes r Description

t%e indicated (uffer si.e. If negative* t%e (uffer si.e is t%e system default1default

Opens a file for reading only. -%e file pointer is placed at t%e (eginning of t%e file. -%is is t%e default mode. Opens a file for reading only in (inary format. -%e file pointer is placed at t%e (eginning of t%e file. -%is is t%e default mode. Opens a file for (ot% reading and riting. -%e file pointer ill (e at t%e (eginning of t%e file. Opens a file for (ot% reading and riting in (inary format. -%e file pointer ill (e at t%e (eginning of t%e file. Opens a file for riting only. Over rites t%e file if t%e file e'ists. If t%e file does not e'ist* creates a ne file for riting. ( Opens a file for riting only in (inary format. Over rites t%e file if t%e file e'ists. If t%e file does not e'ist* creates a ne file for riting.
197 Sree Sakthi Engineering College

r(

rI

r(I

Opens a file for (ot% riting and reading. Over rites t%e e'isting file if t%e file e'ists. If t%e file does not e'ist* creates a ne file for reading and riting. Opens a file for (ot% riting and reading in (inary format. Over rites t%e e'isting file if t%e file e'ists. If t%e file does not e'ist* creates a ne file for reading and riting. Opens a file for appending. -%e file pointer is at t%e end of t%e file if t%e file e'ists. -%at is* t%e file is in t%e append mode. If t%e file does not e'ist* it creates a ne file for riting.

(I a

a(

Opens a file for appending in (inary format. -%e file pointer is at t%e end of t%e file if t%e file e'ists. -%at is* t%e file is in t%e append mode. If t%e file does not e'ist* it creates a ne file for riting.

aI

Opens a file for (ot% appending and reading. -%e file pointer is at t%e end of t%e file if t%e file e'ists. -%e file opens in t%e append mode. If t%e file does not e'ist* it creates a ne file for reading and riting.

a(I

Opens a file for (ot% appending and reading in (inary format. -%e file pointer is at t%e end of t%e file if t%e file e'ists. -%e file opens in t%e append mode. If t%e file does not e'ist* it creates a ne file for reading and riting.

'.1.' The fi"e obCect attributes Once a file is opened and you %ave one file o(4ect* you can get various information related to t%at file. Jere is a list of all attri(utes related to file o(4ect: *ttribute file.closed file.mode file.name file.softspace 0=a-p"e@ SbCusrC(inCpyt%on
198 Sree Sakthi Engineering College

Description Geturns true if file is closed* false ot%er ise. Geturns access mode it% %ic% file as opened. Geturns name of t%e file. Geturns false if space e'plicitly re,uired it% print* true ot%er ise.

S Open a file fo V open13foo.t't3* 3 (32 print 3Name of t%e file: 3* fo.name print 3$losed or not : 3* fo.closed print 3Opening mode : 3* fo.mode print 3Softspace flag : 3* fo.softspace -%is ould produce follo ing result: Name of t%e file: foo.t't $losed or not : /alse Opening mode : ( Softspace flag : : '.1., The c"oseRD #etho$! -%e close12 met%od of a file o(4ect flus%es any un ritten information and closes t%e file o(4ect* after %ic% no more riting can (e done.#yt%on automatically closes a file %en t%e reference o(4ect of a file is reassigned to anot%er file. It is a good practice to use t%e close12 met%od to close a file. S)nta=@ fileO(4ect.close12K 0=a-p"e@ SbCusrC(inCpyt%on S Open a file fo V open13foo.t't3* 3 (32 print 3Name of t%e file: 3* fo.name S $lose opend file fo.close12 -%is ould produce follo ing result:
199 Sree Sakthi Engineering College

Name of t%e file: foo.t't '.1./ Readin( and Writin( Fi"es -%e file o(4ect provides a set of access met%ods to ma+e our lives easier. 5e %o to use read12 and rite12 met%ods to read and rite files. The writeRD 4ethod@ -%e rite12 met%od rites any string to an open file. It is important to note t%at #yt%on rite12 met%od does not add a ne line strings can %ave (inary data and not 4ust te't. -%e c%aracter 10Zn02 to t%e end of t%e string: S)nta=@ fileO(4ect. rite1string2K Jere passed parameter is t%e content to (e ritten into t%e opend file. 0=a-p"e@ SbCusrC(inCpyt%on S Open a file fo V open13foo.t't3* 3 (32 fo. rite1 3#yt%on is a great language.Zn8ea% its greatbbZn32K S $lose opend file fo.close12 -%e a(ove met%od ould create foo.t't file and ould rite given content in t%at file and finally it ould close t%at file. If you ould open t%is file* it ould %ave follo ing content #yt%on is a great language. 8ea% its greatbb The readRD 4ethod@ -%e read12 met%od read a string from an open file. It is important to note t%at #yt%on strings can %ave (inary data and not 4ust te't. ould see

200 Sree Sakthi Engineering College

S)nta=@ fileO(4ect.read1QcountR2K Jere passed parameter is t%e num(er of (ytes to (e read from t%e opend file. -%is met%od starts reading from t%e (eginning of t%e file and if count is missing t%en it tries to read as muc% as possi(le* may (e until t%e end of file. 0=a-p"e@ Let0s ta+e a file foo.t't %ic% e %ave created a(ove. SbCusrC(inCpyt%on S Open a file fo V open13foo.t't3* 3rI32 str V fo.read16:2K print 3Gead String is : 3* str S $lose opend file fo.close12 -%is ould produce follo ing result: Gead String is : #yt%on is '.1.1 Fi"e !ositions -%e tell12 met%od tells you t%e current position it%in t%e file in ot%er ords* t%e ne't read or rite ill occur at t%at many (ytes from t%e (eginning of t%e file: -%e see+1offsetQ* fromR2 met%od c%anges t%e current file position. -%e offset argument indicates t%e num(er of (ytes to (e moved. -%e from argument specifies t%e reference position from %ere t%e (ytes are to (e moved. If from is set to :* it means use t%e (eginning of t%e file as t%e reference position and 6 means use t%e current position as t%e reference position and if it is set to 7 t%en t%e end of t%e file ould (e ta+en as t%e reference position. 0=a-p"e@ Let0s ta+e a file foo.t't %ic% e %ave created a(ove.
201 Sree Sakthi Engineering College

SbCusrC(inCpyt%on S Open a file fo V open13foo.t't3* 3rI32 str V fo.read16:2K print 3Gead String is : 3* str S $%ec+ current position position V fo.tell12K print 3$urrent file position : 3* position S Geposition pointer at t%e (eginning once again position V fo.see+1:* :2K str V fo.read16:2K print 3Again read String is : 3* str S $lose opend file fo.close12 -%is ould produce follo ing result: Gead String is : #yt%on is $urrent file position : 6: Again read String is : #yt%on is '.1.3 Rena-in( and De"etin( Fi"es #yt%on os module provides met%ods t%at %elp you perform file)processing operations* suc% as renaming and deleting files. -o use t%is module you need to import it first and t%en you can all any related functions. The rena-eRD 4ethod@ -%e rename12 met%od ta+es t o arguments* t%e current filename and t%e ne filename.

202 Sree Sakthi Engineering College

S)nta=@ os.rename1currentYfileYname* ne YfileYname2 0=a-p"e@ /ollo ing is t%e e'ample to rename an e'isting file test6.t't: SbCusrC(inCpyt%on import os S Gename a file from test6.t't to test7.t't os.rename1 3test6.t't3* 3test7.t't3 2 The de"eteRD #etho$! 8ou can use t%e delete() met%od to delete files (y supplying t%e name of t%e file to (e deleted as t%e argument. S%nta ! os.delete1fileYname2 E ample! /ollo ing is t%e e'ample to delete an e'isting file test!.txt: SbCusrC(inCpyt%on import os S &elete file test7.t't os.delete13te't7.t't32 '.1.6 Directories in !)thon All files are contained directories. it%in various directories* and #yt%on %as no pro(lem %andling t%ese too. -%e os module %as several met%ods t%at %elp you create* remove* and c%ange

203 Sree Sakthi Engineering College

The -&dirRD #etho$! 8ou can use t%e mkdir() met%od of t%e os module to create directories in t%e current directory. 8ou need to supply an argument to t%is met%od* directory to (e created. S)nta=@ os.m+dir13ne dir32 0=a-p"e@ /ollo ing is t%e e'ample to create a directory test in t%e current directory: SbCusrC(inCpyt%on import os S $reate a directory 3test3 os.m+dir13test32 The chdirRD #etho$! 8ou can use t%e chdir() met%od to c%ange t%e current directory. -%e c%dir12 met%od ta+es an argument* %ic% is t%e name of t%e directory t%at you ant to ma+e t%e current directory. S%nta ! os.c%dir13ne dir32 0=a-p"e@ /ollo ing is t%e e'ample to go into 3C%omeCne dir3 directory: SbCusrC(inCpyt%on import os S $%anging a directory to 3C%omeCne dir3 os.c%dir13C%omeCne dir32 The (etcwdRD #etho$! -%e getcwd() met%od displays t%e current or+ing directory. S%nta ! os.getc d12
204 Sree Sakthi Engineering College

%ic% contains t%e name of t%e

E ample! /ollo ing is t%e e'ample to give current directory: SbCusrC(inCpyt%on import os S -%is ould give location of t%e current directory os.getc d12 The r-dirRD #etho$! -%e rmdir() met%od deletes t%e directory* %ic% is passed as an argument in t%e met%od. ?efore removing a directory* all t%e contents in it s%ould (e removed. S)nta=@ os.rmdir10dirname02 0=a-p"e@ /ollo ing is t%e e'ample to remove 3CtmpCtest3 directory. It is re,uired to give fully ,ualified name of t%e directory ot%er ise it ould searc% for t%at directory in t%e current directory. SbCusrC(inCpyt%on import os S -%is ould remove 3CtmpCtest3 directory. os.rmdir1 3CtmpCtest3 2 '.1.17 Fi"e & Director) Re"ated 4ethods -%ere are t%ree important sources %ic% provide a ide range of utility met%ods to %andle and manipulate files H directories on 5indo s and Uni' operating systems. -%ey are as follo s:
o o

/ile O(4ect "et%ods: -%e file o(4ect provides functions to manipulate files. OS O(4ect "et%ods.: -%is provides met%ods to process files as ell as directories.

'.3 0rrors *nd 0=ceptions #yt%on provides t o very important features to %andle any une'pected error in your #yt%on programs and to add de(ugging capa(ilities in t%em:
o

0=ception >and"in(@ -%is ould (e covered in t%is tutorial.


205 Sree Sakthi Engineering College

*ssertions@ -%is ould (e covered in Assertions in #yt%on tutorial. %ic% occurs during t%e e'ecution of a program t%at disrupts t%e it%* it raises an

'.3.1 What is 0=ception An e'ception is an event* In general* normal flo of t%e program0s instructions. %en a #yt%on script encounters a situation t%at it can0t cope e'ception. An e'ception is a #yt%on o(4ect t%at represents an error. 5%en a #yt%on script raises an e'ception* it must eit%er %andle t%e e'ception immediately ot%er ise it ould terminate and come out. '.3.# >and"in( an e=ception If you %ave some suspicious code t%at may raise an e'ception* you can defend your program (y placing t%e suspicious code in a tr)@ (loc+. After t%e try: (loc+* include an e=cept@ statement* follo ed (y a (loc+ of code %ic% %andles t%e pro(lem as elegantly as possi(le. S%nta ! Jere is simple synta' of try....except...else (loc+s: try: 8ou do your operations %ereK ...................... e'cept %xception&: If t%ere is @'ceptionI* t%en e'ecute t%is (loc+. e'cept %xception&&: If t%ere is @'ceptionII* t%en e'ecute t%is (loc+. ...................... else: If t%ere is no e'ception t%en e'ecute t%is (loc+. Jere are fe important points a(ove t%e a(ove mentioned synta':

A single try statement can %ave multiple e'cept statements. -%is is useful (loc+ contains statements t%at may t%ro different types of e'ceptions. 8ou can also provide a generic e'cept clause* %ic% %andles any e'ception.

%en t%e try

206 Sree Sakthi Engineering College

After t%e e'cept clause1s2* you can include an else)clause. -%e code in t%e else)(loc+ e'ecutes if t%e code in t%e try: (loc+ does not raise an e'ception. -%e else)(loc+ is a good place for code t%at does not need t%e try: (loc+0s protection. %ic% opens a file and rites t%e content in t%e file and comes out

0=a-p"e@ Jere is simple e'ample gracefully (ecause t%ere is no pro(lem at all: SbCusrC(inCpyt%on try: f% V open13testfile3* 3 32 f%. rite13-%is is my test file for e'ception %andlingbb32 e'cept IO@rror: print 3@rror: canZ0t find file or read data3 else: print 35ritten content in t%e file successfully3 f%.close12 -%is ill produce follo ing result: 5ritten content in t%e file successfully 0=a-p"e@ Jere is one more simple e'ample %ic% tries to open a file %ere you do not %ave permission to rite in t%e file so it raises an e'ception: SbCusrC(inCpyt%on try: f% V open13testfile3* 3 32 f%. rite13-%is is my test file for e'ception %andlingbb32 e'cept IO@rror: print 3@rror: canZ0t find file or read data3
207 Sree Sakthi Engineering College

else: print 35ritten content in t%e file successfully3 -%is ill produce follo ing result: @rror: can0t find file or read data '.3.$ The e cept c"ause with no e=ceptions 8ou can also use t%e e'cept statement it% no e'ceptions defined as follo s: try: 8ou do your operations %ereK ...................... e'cept: If t%ere is any e'ception* t%en e'ecute t%is (loc+. ...................... else: If t%ere is no e'ception t%en e'ecute t%is (loc+. -%is +ind of a tr)8e=cept statement catc%es all t%e e'ceptions t%at occur. Using t%is +ind of try) e'cept statement is not considered a good programming practice* t%oug%* (ecause it catc%es all e'ceptions (ut does not ma+e t%e programmer identify t%e root cause of t%e pro(lem t%at may occur. '.3.' The e cept c"ause with -u"tip"e e=ceptions 8ou can also use t%e same except statement to %andle multiple e'ceptions as follo s: try: 8ou do your operations %ereK ...................... e'cept1@'ception6Q* @'ception7Q*...@'ceptionNRRR2: If t%ere is any e'ception from t%e given e'ception list* t%en e'ecute t%is (loc+. ...................... else:
208 Sree Sakthi Engineering College

If t%ere is no e'ception t%en e'ecute t%is (loc+. '.3., The tr)8fina"") c"ause 8ou can use a fina"")@ (loc+ along it% a tr)@ (loc+. -%e finally (loc+ is a place to put any code t%at must e'ecute* statement is t%is: try: 8ou do your operations %ereK ...................... &ue to any e'ception* t%is may (e s+ipped. finally: -%is ould al ays (e e'ecuted. ...................... Note t%at you can provide e'cept clause1s2* or a finally clause* (ut not (ot%. 8ou can not use else clause as ell along it% a finally clause. 0=a-p"e@ SbCusrC(inCpyt%on try: f% V open13testfile3* 3 32 f%. rite13-%is is my test file for e'ception %andlingbb32 finally: print 3@rror: canZ0t find file or read data3 If you do not %ave permission to open t%e file in result: @rror: can0t find file or read data Same e'ample can (e ritten more cleanly as follo s: SbCusrC(inCpyt%on riting mode t%en t%is ill produce follo ing %et%er t%e try)(loc+ raised an e'ception or not. -%e synta' of t%e try)finally

209 Sree Sakthi Engineering College

try: f% V open13testfile3* 3 32 try: f%. rite13-%is is my test file for e'ception %andlingbb32 finally: f%.close12 e'cept IO@rror: print 3@rror: canZ0t find file or read data3 5%en an e'ception is t%ro n in t%e try (loc+* t%e e'ecution immediately passes to t%e finally (loc+. After all t%e statements in t%e finally (loc+ are e'ecuted* t%e e'ception is raised again and is %andled in t%e except statements if present in t%e ne't %ig%er layer of t%e try'except statement. '.3./ *r(u-ent of an 0=ception An e'ception can %ave an argument* %ic% is a value t%at gives additional information a(out t%e pro(lem. -%e contents of t%e argument vary (y e'ception. 8ou capture an e'ception0s argument (y supplying a varia(le in t%e e'cept clause as follo s: try: 8ou do your operations %ereK ...................... e'cept %xception(ype) *rgument: 8ou can print value of Argument %ere... If you are riting t%e code to %andle a single e'ception* you can %ave a varia(le follo t%e name of t%e e'ception in t%e e'cept statement. If you are trapping multiple e'ceptions* you can %ave a varia(le follo t%e tuple of t%e e'ception. -%is varia(le ill receive t%e value of t%e e'ception mostly containing t%e cause of t%e e'ception. -%e varia(le can receive a single value or multiple values in t%e form of a tuple. -%is tuple usually contains t%e error string* t%e error num(er* and an error location. 0=a-p"e@ /ollo ing is an e'ample for a single e'ception:
210 Sree Sakthi Engineering College

SbCusrC(inCpyt%on S &efine a function %ere. def tempYconvert1var2: try: return int1var2 e'cept ]alue@rror* Argument: print 3-%e argument does not contain num(ersZn3* Argument S $all a(ove function %ere. tempYconvert13'y.32K -%is ould produce follo ing result: -%e argument does not contain num(ers invalid literal for int12 it% (ase 6:: 0'y.0 '.3.1 Raisin( an e=ceptions 8ou can raise e'ceptions in several ays (y using t%e raise statement. -%e general synta' for t%e raise statement. S)nta=@ raise Q@'ception Q* args Q* trace(ac+RRR Jere %xception is t%e type of e'ception 1for e'ample* Name@rror2 and argument is a value for t%e e'ception argument. -%e argument is optionalK if not supplied* t%e e'ception argument is None. -%e final argument* trace(ac+* is also optional 1and rarely used in practice2* and* if present* is t%e trace(ac+ o(4ect used for t%e e'ception 0=a-p"e@ An e'ception can (e a string* a class* or an o(4ect. "ost of t%e e'ceptions t%at t%e #yt%on core raises are classes* it% an argument t%at is an instance of t%e class. &efining ne e'ceptions is ,uite easy and can (e done as follo s:
211 Sree Sakthi Engineering College

def functionName1 level 2: if level T 6: raise 3Invalid levelb3* level S -%e code (elo to t%is ould not (e e'ecuted S if e raise t%e e'ception Note@ In order to catc% an e'ception* an 3e'cept3 clause must refer to t%e same e'ception t%ro n eit%er class o(4ect or simple string. /or e'ample to capture a(ove e'ception e'cept clause as follo s: try: ?usiness Logic %ere... e'cept 3Invalid levelb3: @'ception %andling %ere... else: Gest of t%e code %ere... '.3.3 User8Defined 0=ceptions #yt%on also allo s you to create your o n e'ceptions (y deriving classes from t%e standard (uilt)in e'ceptions. Jere is an e'ample related to +untime%rror. Jere a class is created t%at is su(classed from +untime%rror. -%is is useful e'ception is caug%t. In t%e try (loc+* t%e user)defined e'ception is raised and caug%t in t%e e'cept (loc+. -%e varia(le e is used to create an instance of t%e class Net or+error. class Net or+error1Guntime@rror2: def YYinitYY1self* arg2: self.args V arg So once you defined a(ove class* you can raise your e'ception as follo s: try: raise Net or+error13?ad %ostname32
212 Sree Sakthi Engineering College

e must

rite our

%en you need to display more specific information

%en an

e'cept Net or+error*e: print e.args '.6 Functions A function is a (loc+ of organi.ed* reusa(le code t%at is used to perform a single* related action. /unctions provides (etter modularity for your application and a %ig% degree of code reusing. As you already +no * #yt%on gives you many (uilt)in functions li+e print12 etc. (ut you can also create your o n functions. -%ese functions are called user)defined functions. '.6.1 Definin( a Function 8ou can define functions to provide t%e re,uired functionality. Jere are simple rules to define a function in #yt%on: o /unction (loc+s (egin parent%eses 1 1 2 2. o Any input parameters or arguments s%ould (e placed also define parameters inside t%ese parent%eses. o -%e first statement of a function can (e an optional statement ) t%e documentation string of t%e function or docstring. o -%e code (loc+ it%in every function starts it% a colon 1:2 and is indented. o -%e statement return Qe'pressionR e'its a function* optionally passing (ac+ an e'pression to t%e caller. A return statement it% no arguments is t%e same as return None. S)nta=@ def functionname1 parameters 2: 3functionYdocstring3 functionYsuite return Qe'pressionR ?y default* parameters %ave a positional (e%avior* and you need to inform t%em in t%e same order t%at t%ey ere defined.
213 Sree Sakthi Engineering College

it% t%e +ey ord def follo ed (y t%e function name and it%in t%ese parent%eses. 8ou can

0=a-p"e@ Jere is t%e simplest form of a #yt%on function. -%is function ta+es a string as input parameter and prints it on standard screen. def printme1 str 2: 3-%is prints a passed string into t%is function3 print str return '.6.# Ca""in( a Function &efining a function only gives it a name* specifies t%e parameters t%at are to (e included in t%e function* and structures t%e (loc+s of code.Once t%e (asic structure of a function is finali.ed* you can e'ecute it (y calling it from anot%er function or directly from t%e #yt%on prompt. /ollo ing is t%e e'ample to call printme12 function: SbCusrC(inCpyt%on S /unction definition is %ere def printme1 str 2: 3-%is prints a passed string into t%is function3 print strK returnK S No you can call printme function printme13I0m first call to user defined functionb32K printme13Again second call to t%e same function32K -%is ould produce follo ing result: I0m first call to user defined functionb Again second call to t%e same function

214 Sree Sakthi Engineering College

'.6.$ !ass b) reference %s %a"ue All parameters 1arguments2 in t%e #yt%on language are passed (y reference. It means if you c%ange %at a parameter refers to it%in a function* t%e c%ange also reflects (ac+ in t%e calling function. /or e'ample: SbCusrC(inCpyt%on S /unction definition is %ere def c%angeme1 mylist 2: 3-%is c%anges a passed list into t%is function3 mylist.append1Q6*7*=*>R2K print 3]alues inside t%e function: 3* mylist return S No you can call c%angeme function mylist V Q6:*7:*=:RK c%angeme1 mylist 2K print 3]alues outside t%e function: 3* mylist Jere e are maintaining reference of t%e passed o(4ect and appending values in t%e same o(4ect. So t%is ould produce follo ing result: ]alues inside t%e function: Q6:* 7:* =:* Q6* 7* =* >RR ]alues outside t%e function: Q6:* 7:* =:* Q6* 7* =* >RR -%ere is one more e'ample %ere argument is (eing passed (y reference (ut inside t%e function* (ut t%e reference is (eing over) ritten. SbCusrC(inCpyt%on S /unction definition is %ere def c%angeme1 mylist 2: 3-%is c%anges a passed list into t%is function3
215 Sree Sakthi Engineering College

mylist V Q6*7*=*>RK S -%is ould assig ne reference in mylist print 3]alues inside t%e function: 3* mylist return S No you can call c%angeme function mylist V Q6:*7:*=:RK c%angeme1 mylist 2K print 3]alues outside t%e function: 3* mylist -%e parameter mylist is local to t%e function c%angeme. $%anging mylist follo ing result: ]alues inside t%e function: Q6* 7* =* >R ]alues outside t%e function: Q6:* 7:* =:R '.6.' Function *r(u-ents 8ou can call a function (y using t%e follo ing types of formal arguments::
o o o o

it%in t%e function ould produce

does not affect mylist. -%e function accomplis%es not%ing and finally t%is

Ge,uired arguments !ey ord arguments &efault arguments ]aria(le)lengt% arguments

'.6.'.1 Re;uired ar(u-ents@ Ge,uired arguments are t%e arguments passed to a function in correct positional order. Jere t%e num(er of arguments in t%e function call s%ould matc% e'actly it% t%e function definition. -o call t%e function printme() you definitely need to pass one argument ot%er ise it ould give a synta' error as follo s: SbCusrC(inCpyt%on S /unction definition is %ere def printme1 str 2:
216 Sree Sakthi Engineering College

3-%is prints a passed string into t%is function3 print strK returnK S No you can call printme function printme12K -%is ould produce follo ing result: -race(ac+ 1most recent call last2: /ile 3test.py3* line 66* in TmoduleP printme12K -ype@rror: printme12 ta+es e'actly 6 argument 1: given2 '.6.'.# Be)word ar(u-ents@ !ey ord arguments are related to t%e function calls. 5%en you use +ey ord arguments in a function call* t%e caller identifies t%e arguments (y t%e parameter name. -%is allo s you to s+ip arguments or place t%em out of order (ecause t%e #yt%on interpreter is a(le to use t%e +ey ords provided to matc% t%e values it% parameters. 8ou can also ma+e +ey ord calls to t%e printme() function in t%e follo ing ays: SbCusrC(inCpyt%on S /unction definition is %ere def printme1 str 2: 3-%is prints a passed string into t%is function3 print strK returnK S No you can call printme function printme1 str V 3"y string32K -%is ould produce follo ing result:
217 Sree Sakthi Engineering College

"y string /ollo ing e'ample gives more clear picture. Note* %ere order of t%e parameter does not matter: SbCusrC(inCpyt%on S /unction definition is %ere def printinfo1 name* age 2: 3-%is prints a passed info into t%is function3 print 3Name: 3* nameK print 3Age 3* ageK returnK S No you can call printinfo function printinfo1 ageV<:* nameV3mi+i3 2K -%is ould produce follo ing result: Name: mi+i Age <: '.6.'.$ Defau"t ar(u-ents@ A default argument is an argument t%at assumes a default value if a value is not provided in t%e function call for t%at argument. /ollo ing e'ample gives idea on default arguments* it ould print default age if it is not passed: SbCusrC(inCpyt%on S /unction definition is %ere def printinfo1 name* age V =< 2: 3-%is prints a passed info into t%is function3 print 3Name: 3* nameK print 3Age 3* ageK returnK
218 Sree Sakthi Engineering College

S No you can call printinfo function printinfo1 ageV<:* nameV3mi+i3 2K printinfo1 nameV3mi+i3 2K -%is ould produce follo ing result: Name: mi+i Age <: Name: mi+i Age =< '.6.'.' Kariab"e8"en(th ar(u-ents@ 8ou may need to process a function for more arguments t%an you specified in t%e function definition* unli+e re,uired and default arguments. -%e general synta' for a function it% non)+ey ord varia(le arguments is t%is: def functionname1QformalYargs*R WvarYargsYtuple 2: 3functionYdocstring3 functionYsuite return Qe'pressionR An asteris+ 1W2 is placed (efore t%e varia(le name t%at specified during t%e function call. /or e'ample: SbCusrC(inCpyt%on S /unction definition is %ere def printinfo1 arg6* Wvartuple 2: 3-%is prints a varia(le passed arguments3 print 3Output is: 3 print arg6
219 Sree Sakthi Engineering College

%ile

defining t%e function. -%ese arguments are called variable'length arguments and are not named

ill %old t%e values of all

non+ey ord varia(le arguments. -%is tuple remains empty if no additional arguments are

for var in vartuple: print var returnK S No you can call printinfo function printinfo1 6: 2K printinfo1 E:* B:* <: 2K -%is ould produce follo ing result: Output is: 6: Output is: E: B: <: '.6., The *non)-ous Functions 8ou can use t%e lambda +ey ord to create small anonymous functions. -%ese functions are called anonymous (ecause t%ey are not declared in t%e standard manner (y using t%e def +ey ord.
o

Lam(da forms can ta+e any num(er of arguments (ut return 4ust one value in t%e form of an e'pression. -%ey cannot contain commands or multiple e'pressions. An anonymous function cannot (e a direct call to print (ecause lam(da re,uires an e'pression. Lam(da functions %ave t%eir o n local namespace and cannot access varia(les ot%er t%an t%ose in t%eir parameter list and t%ose in t%e glo(al namespace. Alt%oug% it appears t%at lam(da0s are a one)line version of a function* t%ey are not e,uivalent to inline statements in $ or $II* %ose purpose is (y passing function stac+ allocation during invocation for performance reasons.

S)nta=@ -%e synta' of lambda functions contains only a single statement* %ic% is as follo s:
220 Sree Sakthi Engineering College

lam(da Qarg6 Q*arg7*.....argnRR:e'pression 0=a-p"e@ /ollo ing is t%e e'ample to s%o %o lembda form of function or+s: SbCusrC(inCpyt%on S /unction definition is %ere sum V lam(da arg6* arg7: arg6 I arg7K S No you can call sum as a function print 3]alue of total : 3* sum1 6:* 7: 2 print 3]alue of total : 3* sum1 7:* 7: 2 -%is ould produce follo ing result: ]alue of total : =: ]alue of total : >: '.6./ The return State-ent -%e statement return Qe'pressionR e'its a function* optionally passing (ac+ an e'pression to t%e caller. A return statement it% no arguments is t%e same as return None All t%e a(ove e'amples are not returning any value* (ut if you li+e you can return a value from a function as follo s: SbCusrC(inCpyt%on S /unction definition is %ere def sum1 arg6* arg7 2: S Add (ot% t%e parameters and return t%em.3 total V arg6 I arg7 print 3Inside t%e function : 3* total return totalK S No you can call sum function
221 Sree Sakthi Engineering College

total V sum1 6:* 7: 2K print 3Outside t%e function : 3* total -%is ould produce follo ing result: Inside t%e function : =: Outside t%e function : =: '.6.1 Scope of Kariab"es All varia(les in a program may not (e accessi(le at all locations in t%at program. -%is depends on %ere you %ave declared a varia(le. -%e scope of a varia(le determines t%e portion of t%e program %ere you can access a particular identifier. -%ere are t o (asic scopes of varia(les in #yt%on:

Glo(al varia(les Local varia(les

'.6.1.1 ."oba" %s. 2oca" %ariab"es ]aria(les t%at are defined inside a function (ody %ave a local scope* and t%ose defined outside %ave a glo(al scope. -%is means t%at local varia(les can (e accessed only inside t%e function in %ic% t%ey are declared %ereas glo(al varia(les can (e accessed t%roug%out t%e program (ody (y all functions. 5%en you call a function* t%e varia(les declared inside it are (roug%t into scope. 0=a-p"e@ SbCusrC(inCpyt%on total V :K S -%is is glo(al varia(le. S /unction definition is %ere def sum1 arg6* arg7 2: S Add (ot% t%e parameters and return t%em.3 total V arg6 I arg7K S Jere total is local varia(le. print 3Inside t%e function local total : 3* total return totalK
222 Sree Sakthi Engineering College

S No you can call sum function sum1 6:* 7: 2K print 3Outside t%e function glo(al total : 3* total -%is ould produce follo ing result: Inside t%e function local total : =: Outside t%e function glo(al total : : '.17 4odu"es A module allo s you to logically organi.e your #yt%on code. Grouping related code into a module ma+es t%e code easier to understand and use. A module is a #yt%on o(4ect it% ar(itrarily named attri(utes t%at you can (ind and reference. Simply* a module is a file consisting of #yt%on code. A module can define functions* classes* and varia(les. A module can also include runna(le code. 0=a-p"e@ -%e #yt%on code for a module named aname normally resides in a file named aname.py. Jere0s an e'ample of a simple module* %ello.py def printYfunc1 par 2: print 3Jello : 3* par return '.17.1The i-port State-ent 8ou can use any #yt%on source file as a module (y e'ecuting an import statement in some ot%er #yt%on source file. import %as t%e follo ing synta': import module6Q* module7Q*... moduleNR 5%en t%e interpreter encounters an import statement* it imports t%e module if t%e module is present in t%e searc% pat%. Asearc% pat% is a list of directories t%at t%e interpreter searc%es (efore importing a module. 0=a-p"e@ -o import t%e module %ello.py* you need to put t%e follo ing command at t%e top of t%e script:
223 Sree Sakthi Engineering College

SbCusrC(inCpyt%on S Import module %ello import %ello S No you can call defined function t%at module as follo s %ello.printYfunc13\ara32 -%is ould produce follo ing result: Jello : \ara A module is loaded only once* regardless of t%e num(er of times it is imported. -%is prevents t%e module e'ecution from %appening over and over again if multiple imports occur. '.17.# The fro-...i-port State-ent #yt%on0s from statement lets you import specific attri(utes from a module into t%e current namespace: S)nta=@ from modname import name6Q* name7Q* ... nameNRR 0=a-p"e@ /or e'ample* to import t%e function fi(onacci from t%e module fi(* use t%e follo ing statement: from fi( import fi(onacci -%is statement does not import t%e entire module fi( into t%e current namespaceK it 4ust introduces t%e item fi(onacci from t%e module fi( into t%e glo(al sym(ol ta(le of t%e importing module. '.17.$ The fro-...i-port S State-ent It is also possi(le to import all names from a module into t%e current namespace (y using t%e follo ing import statement: from modname import W
224 Sree Sakthi Engineering College

-%is provides an easy ay to import all t%e items from a module into t%e current namespaceK %o ever* t%is statement s%ould (e used sparingly. '.17.' 2ocatin( 4odu"es 5%en you import a module* t%e #yt%on interpreter searc%es for t%e module in t%e follo ing se,uences:

-%e current directory. If t%e module isn0t found* #yt%on t%en searc%es eac% directory in t%e s%ell varia(le #8-JON#A-J. If all else fails* #yt%on c%ec+s t%e default pat%. On UNIX* t%is default pat% is normally CusrClocalCli(Cpyt%onC.

-%e module searc% pat% is stored in t%e system module sys as t%e s)s.path varia(le. -%e sys.pat% varia(le contains t%e current directory* #8-JON#A-J* and t%e installation)dependent default. '.17., The !9T>ON!*T> Kariab"e -%e #8-JON#A-J is an environment varia(le* consisting of a list of directories. -%e synta' of #8-JON#A-J is t%e same as t%at of t%e s%ell varia(le #A-J. Jere is a typical #8-JON#A-J from a 5indo s system: set #8-JON#A-JVc:Zpyt%on7:Zli(K And %ere is a typical #8-JON#A-J from a UNIX system: set #8-JON#A-JVCusrClocalCli(Cpyt%on '.17./ Na-espaces and Scopin( ]aria(les are names 1identifiers2 t%at map to o(4ects. A namespace is a dictionary of varia(le names 1+eys2 and t%eir corresponding o(4ects 1values2. A #yt%on statement can access varia(les in a local namespace and in t%e global namespace. If a local and a glo(al varia(le %ave t%e same name* t%e local varia(le s%ado s t%e glo(al varia(le.

225 Sree Sakthi Engineering College

@ac% function %as its o n local namespace. $lass met%ods follo assumes t%at any varia(le assigned a value in a function is local. -%erefore* in order to assign a value to a glo(al varia(le glo(al statement.

t%e same scoping rule

as ordinary functions.#yt%on ma+es educated guesses on %et%er varia(les are local or glo(al. It it%in a function* you must first use t%e

-%e statement global ,ar-ame tells #yt%on t%at ]arName is a glo(al varia(le. #yt%on stops searc%ing t%e local namespace for t%e varia(le. /or e'ample* .oney* e define a varia(le .oney in t%e glo(al namespace. 5it%in t%e function e assign .oney a value . t%erefor #yt%on assumes .oney is a local varia(le. Jo ever*

e access t%e value of t%e local varia(le .oney (efore setting it* so an Un(oundLocal@rror is t%e result. Uncommenting t%e glo(al statement fi'es t%e pro(lem. SbCusrC(inCpyt%on "oney V 7::: def Add"oney12: S Uncomment t%e follo ing line to fi' t%e code: S glo(al "oney "oney V "oney I 6 print "oney Add"oney12 print "oney '.17.1 The dirR D Function -%e dir12 (uilt)in function returns a sorted list of strings containing t%e names defined (y a module.-%e list contains t%e names of all t%e modules* varia(les* and functions t%at are defined in a module. 0=a-p"e@ SbCusrC(inCpyt%on
226 Sree Sakthi Engineering College

S Import (uilt)in module mat% import mat% content V dir1mat%2 print contentK -%is ould produce follo ing result: Q0YYdocYY0* 0YYfileYY0* 0YYnameYY0* 0acos0* 0asin0* 0atan0* 0atan70* 0ceil0* 0cos0* 0cos%0* 0degrees0* 0e0* 0e'p0* 0fa(s0* 0floor0* 0fmod0* 0fre'p0* 0%ypot0* 0lde'p0* 0log0* 0log6:0* 0modf0* 0pi0* 0po 0* 0radians0* 0sin0* 0sin%0* 0s,rt0* 0tan0* 0tan%0R Jere t%e special string varia(le ""name"" is t%e module0s name* and ""file"" is t%e filename from %ic% t%e module as loaded. '.17.3 The ("oba"sRD and "oca"sRD Functions -%e globals() and locals() functions can (e used to return t%e names in t%e glo(al and local namespaces depending on t%e location from If glo(als12 is called from %ere t%ey are called.If locals12 is called from ill return all t%e names t%at can (e it%in a function* it ill return all t%e names t%at can (e accessed locally from t%at function. it%in a function* it accessed glo(ally from t%at function.-%e return type of (ot% t%ese functions is dictionary. -%erefore* names can (e e'tracted using t%e +eys12 function. The reloa$&' Function@ 5%en t%e module is imported into a script* t%e code in t%e top)level portion of a module is e'ecuted only once. -%erefore* if you S)nta=@ -%e synta' of t%e reload12 function is t%is:
227 Sree Sakthi Engineering College

ant to ree'ecute t%e top)level code in a module* you can use t%e reload()

function. -%e reload12 function imports a previously imported module again.

reload1moduleYname2 Jere module"name is t%e name of t%e module you

ant to reload and not t%e string containing

t%e module name. /or e'ample to re)load hello module* do t%e follo ing: reload1%ello2 '.17.6 !ac&a(es in !)thon A pac+age is a %ierarc%ical file directory structure t%at defines a single #yt%on application environment t%at consists of modules and su(pac+ages and su()su(pac+ages* and so on. 0=a-p"e@ $onsider a file Pots.py availa(le in Phone directory. -%is file %as follo ing line of source code: SbCusrC(inCpyt%on def #ots12: print 3I0m #ots #%one3 Similar ay e %ave anot%er t o files %aving different functions it% t%e same name as a(ove: o Phone/&sdn.py file %aving function Isdn12 o Phone//0.py file %aving function G=12 o No create one more file YYinitYY.py in Phone directory : o #%oneCYYinitYY.py -o ma+e all of your functions availa(le %en you0ve imported #%one* you need to put e'plicit import statements in YYinitYY.py as follo s: from #ots import #ots from Isdn import Isdn from G= import G= After you0ve added t%ese lines to YYinitYY.py* you %ave all of t%ese classes availa(le %en you0ve imported t%e #%one pac+age: SbCusrC(inCpyt%on

228 Sree Sakthi Engineering College

S No import your #%one #ac+age. import #%one #%one.#ots12 #%one.Isdn12 #%one.G=12 -%is ould produce follo ing result: I0m #ots #%one I0m =G #%one I0m IS&N #%one Note@ In t%e a(ove e'ample* e %ave ta+en e'ample of a single functions in eac% file* (ut you

can +eep multiple functions in your files. 8ou can also define different #yt%on classes in t%ose files and t%en you can create your pac+ages out of t%ose classes. 17.1 What are 4odu"es 17.# 4odu"es and Fi"es 17.$ Na-espaces 17.' I-portin( 4odu"es 17., I-portin( 4odu"e *ttributes 17./ 4odu"e 5ui"t8in Functions 17.1 !ac&a(es 17.3 Other Features of 4odu"es '.11 C"asses and OO! #yt%on %as (een an o(4ect)oriented language from day one. ?ecause of t%is* creating and using classes and o(4ects are do nrig%t easy. -%is c%apter %elps you (ecome an e'pert in using #yt%on0s o(4ect)oriented programming support.

229 Sree Sakthi Engineering College

'.11.1 O%er%iew of OO! Ter-ino"o() C"ass@ A user)defined prototype for an o(4ect t%at defines a set of attri(utes t%at c%aracteri.e any o(4ect of t%e class. -%e attri(utes are data mem(ers 1class varia(les and instance varia(les2 and met%ods* accessed via dot notation. C"ass %ariab"e@ A varia(le t%at is s%ared (y all instances of a class. $lass varia(les are defined it%in a class (ut outside any of t%e class0s met%ods. $lass varia(les aren0t used as Data -e-ber@ A class varia(le or instance varia(le t%at %olds data associated class and its o(4ects. Function o%er"oadin(@ -%e assignment of more t%an one (e%avior to a particular function. -%e operation performed varies (y t%e types of o(4ects 1arguments2 involved. Instance %ariab"e@ A varia(le t%at is defined inside a met%od and (elongs only to t%e current instance of a class. Inheritance @ -%e transfer of t%e c%aracteristics of a class to ot%er classes t%at are derived from it. Instance@ An individual o(4ect of a certain class. An o(4ect o(4 t%at (elongs to a class $ircle* for e'ample* is an instance of t%e class $ircle. Instantiation @ -%e creation of an instance of a class. 4ethod @ A special +ind of function t%at is defined in a class definition. ObCect @ A uni,ue instance of a data structure t%at0s defined (y its class. An o(4ect comprises (ot% data mem(ers 1class varia(les and instance varia(les2 and met%ods. Operator o%er"oadin(@ -%e assignment of more t%an one function to a particular operator. '.11.# Creatin( C"asses -%e class statement creates a ne class definition. -%e name of t%e class immediately follo s t%e +ey ord class follo ed (y a colon as follo s: class $lassName:
230 Sree Sakthi Engineering College

fre,uently as instance varia(les are. it% a

0Optional class documentation string0


o o

classYsuite -%e class %as a documentation string %ic% can (e access via 1lass-ame.""doc"". -%e class"suite consists of all t%e component statements* defining class mem(ers* data attri(utes* and functions.

0=a-p"e@ /ollo ing is t%e e'ample of a simple #yt%on class: class @mployee: 0$ommon (ase class for all employees0 emp$ount V : def YYinitYY1self* name* salary2: self.name V name self.salary V salary @mployee.emp$ount IV 6 def display$ount1self2: print 3-otal @mployee ;d3 ; @mployee.emp$ount def display@mployee1self2:
o

print 3Name : 3* self.name* 3* Salary: 3* self.salary -%e varia(le emp1ount is a class varia(le %ose value ould (e s%ared among all instances of a t%is class. -%is can (e accessed as %mployee.emp1ount from inside t%e class or outside t%e class. -%e first met%od ""init""() is a special met%od %ic% is called class constructor or initiali.ation met%od t%at #yt%on calls %en you create a ne instance of t%is class. 8ou declare ot%er class met%ods li+e normal functions it% t%e e'ception t%at t%e first argument to eac% met%od is self. #yt%on adds t%e self argument to t%e list for youK you don0t need to include it %en you call t%e met%ods.
231 Sree Sakthi Engineering College

'.11.$ Creatin( instance obCects -o create instances of a class* you call t%e class using class name and pass in %atever arguments its ""init"" met%od accepts. 3-%is ould create first o(4ect of @mployee class3 emp6 V @mployee13\ara3* 7:::2 3-%is ould create second o(4ect of @mployee class3 emp7 V @mployee13"anni3* <:::2 '.11.' *ccessin( attributes@ 8ou access t%e o(4ect0s attri(utes using t%e dot operator it% o(4ect. $lass varia(le ould (e accessed using class name as follo s: emp6.display@mployee12 emp7.display@mployee12 print 3-otal @mployee ;d3 ; @mployee.emp$ount No putting it all toget%er: SbCusrC(inCpyt%on class @mployee: 0$ommon (ase class for all employees0 emp$ount V : def YYinitYY1self* name* salary2: self.name V name self.salary V salary @mployee.emp$ount IV 6 def display$ount1self2: print 3-otal @mployee ;d3 ; @mployee.emp$ount

232 Sree Sakthi Engineering College

def display@mployee1self2: print 3Name : 3* self.name* 3* Salary: 3* self.salary 3-%is ould create first o(4ect of @mployee class3 emp6 V @mployee13\ara3* 7:::2 3-%is ould create second o(4ect of @mployee class3 emp7 V @mployee13"anni3* <:::2 emp6.display@mployee12 emp7.display@mployee12 print 3-otal @mployee ;d3 ; @mployee.emp$ount -%is ould produce follo ing result: Name : \ara *Salary: 7::: Name : "anni *Salary: <::: -otal @mployee 7 8ou can add* remove* or modify attri(utes of classes and o(4ects at any time: emp6.age V E S Add an 0age0 attri(ute. emp6.age V 9 S "odify 0age0 attri(ute. del emp6.age S &elete 0age0 attri(ute. Instead of using t%e normal statements to access attri(utes* you can use follo ing functions:
o o o

-%e (etattrRobC? na-eY? defau"tZD : to access t%e attri(ute of o(4ect. -%e hasattrRobC?na-eD : to c%ec+ if an attri(ute e'ists or not. -%e setattrRobC?na-e?%a"ueD : to set an attri(ute. If attri(ute does not e'ist t%en it ould (e created. -%e de"attrRobC? na-eD : to delete an attri(ute. S Geturns true if 0age0 attri(ute e'ists S Geturns value of 0age0 attri(ute S &elete attri(ute 0age0
233 Sree Sakthi Engineering College

%asattr1emp6* 0age02 getattr1emp6* 0age02 delattr1empl* 0age02

setattr1emp6* 0age0* 92 S Set attri(ute 0age0 at 9

'.11., 5ui"t8In C"ass *ttributes @very #yt%on class +eeps follo ing (uilt)in attri(utes and t%ey can (e accessed using dot operator li+e any ot%er attri(ute:
o o o o

EEdictEE @ &ictionary containing t%e class0s namespace. EEdocEE @ $lass documentation string* or None if undefined. EEna-eEE@ $lass name. EE-odu"eEE@ "odule name in %ic% t%e class is defined. -%is attri(ute is 3YYmainYY3 in interactive mode. EEbasesEE @ A possi(ly empty tuple containing t%e (ase classes* in t%e order of t%eir occurrence in t%e (ase class list.

/or t%e a(ove class let0s try to access all t%ese attri(utes: print 3@mployee.YYdocYY:3* @mployee.YYdocYY print 3@mployee.YYnameYY:3* @mployee.YYnameYY print 3@mployee.YYmoduleYY:3* @mployee.YYmoduleYY print 3@mployee.YY(asesYY:3* @mployee.YY(asesYY print 3@mployee.YYdictYY:3* @mployee.YYdictYY -%is ould produce follo ing result: @mployee.YYdocYY: $ommon (ase class for all employees @mployee.YYnameYY: @mployee @mployee.YYmoduleYY: YYmainYY @mployee.YY(asesYY: 12 @mployee.YYdictYY: ^0YYmoduleYY0: 0YYmainYY0* 0display$ount0: Tfunction display$ount at :'(Ec9>DD>P* 0emp$ount0: 7* 0display@mployee0: Tfunction display@mployee at :'(Ec9>>6cP* 0YYdocYY0: 0$ommon (ase class for all employees0* 0YYinitYY0: Tfunction YYinitYY at :'(Ec9>B(cP`

234 Sree Sakthi Engineering College

'.11./ Destro)in( ObCects R.arba(e Co""ectionD #yt%on deletes unneeded o(4ects 1(uilt)in types or class instances2 automatically to free memory space. -%e process (y %ic% #yt%on periodically reclaims (loc+s of memory t%at no longer are in use is termed gar(age collection. #yt%on0s gar(age collector runs during program e'ecution and is triggered %en an o(4ect0s reference count reac%es .ero. An o(4ect0s reference count c%anges as t%e num(er of aliases t%at point to it c%anges: An o(4ect0s reference count increases %en it0s assigned a ne name or placed in a container 1list* tuple* or dictionary2. -%e o(4ect0s reference count decreases %en it0s deleted it% del* its reference is reassigned* or its reference goes out of scope. 5%en an o(4ect0s reference count reac%es .ero* #yt%on collects it automatically. a V >: (Va c V Q(R del a ( V 6:: S $reate o(4ect T>:P S Increase ref. count of T>:P S Increase ref. count of T>:P S &ecrease ref. count of T>:P S &ecrease ref. count of T>:P

cQ:R V )6 S &ecrease ref. count of T>:P 8ou normally on0t notice %en t%e gar(age collector destroys an orp%aned instance and reclaims its space. ?ut a class can implement t%e special met%od ""del""()* called a destructor* t%at is invo+ed 0=a-p"e@ -%is YYdelYY12 destructor prints t%e class name of an instance t%at is a(out to (e destroyed: SbCusrC(inCpyt%on class #oint: def YYinit1 self* 'V:* yV:2:
235 Sree Sakthi Engineering College

%en t%e instance is a(out to (e destroyed. -%is met%od mig%t (e used to clean

up any nonmemory resources used (y an instance.

self.' V ' self.y V y def YYdelYY1self2: classYname V self.YYclassYY.YYnameYY print classYname* 3destroyed3 pt6 V #oint12 pt7 V pt6 pt= V pt6 print id1pt62* id1pt72* id1pt=2 S prints t%e ids of t%e o(e4cts del pt6 del pt7 del pt= -%is ould produce follo ing result: =:9=>:6=7> =:9=>:6=7> =:9=>:6=7> #oint destroyed '.11.1 C"ass Inheritance Instead of starting from scratc%* you can create a class (y deriving it from a pree'isting class (y listing t%e parent class in parent%eses after t%e ne class name. -%e c%ild class in%erits t%e attri(utes of its parent class* and you can use t%ose attri(utes as if t%ey S)nta=@ &erived classes are declared muc% li+e t%eir parent classK %o ever* a list of (ase classes to in%erit from are given after t%e class name: class Su($lassName 1#arent$lass6Q* #arent$lass7* ...R2: 0Optional class documentation string0 classYsuite
236 Sree Sakthi Engineering College

ere defined in t%e c%ild class. A c%ild class can also override data mem(ers and

met%ods from t%e parent.

0=a-p"e@ SbCusrC(inCpyt%on class #arent: S define parent class

parentAttr V 6:: def YYinitYY1self2: print 3$alling parent constructor3 def parent"et%od1self2: print 0$alling parent met%od0 def setAttr1self* attr2: #arent.parentAttr V attr def getAttr1self2: print 3#arent attri(ute :3* #arent.parentAttr class $%ild1#arent2: S define c%ild class def YYinitYY1self2: print 3$alling c%ild constructor3 def c%ild"et%od1self2: print 0$alling c%ild met%od0 c V $%ild12 c.c%ild"et%od12 c.parent"et%od12 c.setAttr17::2 S instance of c%ild S c%ild calls its met%od S calls parent0s met%od S again call parent0s met%od
237 Sree Sakthi Engineering College

c.getAttr12 S again call parent0s met%od -%is ould produce follo ing result: $alling c%ild constructor $alling c%ild met%od $alling parent met%od #arent attri(ute : 7:: Similar ay you can drive a class from multiple parent classes as follo s: class A: ..... class ?: ..... class $1A* ?2: S su(class of A and ? ..... 8ou can use issu(class12 or isinstance12 functions to c%ec+ a relations%ips of t o classes and instances:

S define your class A

S define your calss ?

-%e issubc"assRsub? supD (oolean function returns true if t%e given su(class sub is indeed a su(class of t%e superclass sup. -%e isinstanceRobC? C"assD (oolean function returns true if ob is an instance of class 1lass or is an instance of a su(class of $lass

'.11.3 O%erridin( 4ethods 8ou can al ays override your parent class met%ods. One reason for overriding parent0s met%ods is (ecause you may ant special or different functionality in your su(class. 0=a-p"e@ SbCusrC(inCpyt%on class #arent: S define parent class
238 Sree Sakthi Engineering College

def my"et%od1self2: print 0$alling parent met%od0 class $%ild1#arent2: S define c%ild class def my"et%od1self2: print 0$alling c%ild met%od0 c V $%ild12 S instance of c%ild

c.my"et%od12 S c%ild calls overridden met%od -%is ould produce follo ing result: $alling c%ild met%od '.11.6 5ase O%er"oadin( 4ethods /ollo ing ta(le lists some generic functionality t%at you can override in your o n classes: SN 4ethod? Description & Sa-p"e Ca"" EEinitEE R se"f Y?ar(s...Z D 6 $onstructor 1 it% any optional arguments2 Sample $all : ob = class-ame(args) EEde"EER se"f D 7 &estructor* deletes an o(4ect Sample $all : dell ob EEreprEER se"f D = @valuata(le string representation Sample $all : repr(ob ) EEstrEER se"f D > #rinta(le string representation Sample $all : str(ob ) < EEc-pEE R se"f? = D
239 Sree Sakthi Engineering College

O(4ect comparison Sample $all : cmp(ob ) x) '.11.17 O%er"oadin( Operators Suppose you0ve created a ]ector class to represent t o)dimensional vectors. 5%at %appens %en you use t%e plus operator to add t%emA "ost li+ely #yt%on ill yell at you. 8ou could* %o ever* define t%e ""add"" met%od in your class to perform vector addition* and t%en t%e plus operator ould (e%ave as per e'pectation: 0=a-p"e@ SbCusrC(inCpyt%on class ]ector: def YYinitYY1self* a* (2: self.a V a self.( V ( def YYstrYY1self2: return 0]ector 1;d* ;d20 ; 1self.a* self.(2 def YYaddYY1self*ot%er2: return ]ector1self.a I ot%er.a* self.( I ot%er.(2 v6 V ]ector17*6:2 v7 V ]ector1<*)72 print v6 I v7 -%is ould produce follo ing result: ]ector1E*92

240 Sree Sakthi Engineering College

'.11.11 Data >idin( An o(4ect0s attri(utes may or may not (e visi(le outside t%e class definition. /or t%ese cases* you can name attri(utes it% a dou(le underscore prefi'* and t%ose attri(utes ill not (e directly visi(le to outsiders: E ample! SbCusrC(inCpyt%on class Lust$ounter: YYsecret$ount V : def count1self2: self.YYsecret$ount IV 6 print self.YYsecret$ount counter V Lust$ounter12 counter.count12 counter.count12 print counter.YYsecret$ount -%is ould produce follo ing result: 6 7 -race(ac+ 1most recent call last2: /ile 3test.py3* line 67* in TmoduleP print counter.YYsecret$ount Attri(ute@rror: Lust$ounter instance %as no attri(ute 0YYsecret$ount0 #yt%on protects t%ose mem(ers (y internally c%anging t%e name to include t%e class name. 8ou can access suc% attri(utes as ob ect."class-ame""attr-ame. If you ould replace your last line as follo ing* t%en it ould or+ for you:
241 Sree Sakthi Engineering College

......................... print counter.YLust$ounterYYsecret$ount -%is ould produce follo ing result: 6 7 7 '.1# 0=ecution 0n%iron-ent '.1#.1 Ca""ab"e ObCects A num(er of #yt%on o(4ects are %at e descri(e as 3calla(le*3 meaning any o(4ect %ic% can (e invo+ed it% t%e function operator 3123. -%e function operator is placed immediately follo ing t%e name of t%e calla(le to invo+e it. '.1#.1.1 Functions -%ere are t%ree types of different function o(4ects* t%e first (eing t%e #yt%on (uilt)in functions. 5ui"t8in Functions R5IFsD ?I/s are generally ritten as e'tensions in $ or $II* compiled into t%e #yt%on interpreter* and loaded into t%e system as part of t%e first 1(uilt)in2 namespace.

5IF (if.YYdocYY (if.YYnameYY (if.YYselfYY User8defined Functions RUDFsD

*ttribute Description documentation string function name as a string set to None 1reserved for (uilt)in met%ods2

-%ese are generally defined at t%e top)level part of a module and %ence are loaded as part of t%e glo(al namespace 1once t%e (uilt)in namespace %as (een esta(lis%ed2.

UIF udf.YYdocYY udf.YYnameYY udf.funcYcode

*ttribute Description documentation string 1also udf.funcYdoc2 function name as a string 1also udf.funcYname2 (yte)compiled code o(4ect
242 Sree Sakthi Engineering College

udf.funcYdefaults udf.funcYglo(als

default argument tuple glo(al namespace dictionaryK same as calling glo(als1'2 from it%in function

"a-bda 0=pressions RFunctions na-ed OX"a-bdaUOD Lam(da e'pressions are t%e same as user)defined functions it% some minor differences. Alt%oug% t%ey yield function o(4ects* lam(da e'pressions are not created it% t%e def statement and instead are created using t%e "a-bda +ey ord. '.1#.1.# 4ethods "any #yt%on data types suc% as lists and dictionaries also %ave met%ods* +no n as (uilt) in met%ods. 5ui"t8in 4ethods R5I4sD 5I4 *ttribute (im.YYdocYY (im.YYnameYY (im.YYselfYY udf.funcYdefaults udf.funcYglo(als Description documentation string function name as a string o(4ect t%e met%od is (ound to default argument tuple glo(al namespace dictionaryK same as calling glo(als1'2 from it%in function User8defined 4ethods RUD4sD User)defined met%ods are contained in class definitions and are merely 3 rappers3 around standard functions* applica(le only to t%e class t%ey are defined for.

UD4 *ttribute udm.YYdocYY udm.YYnameYY udm.imYclass udm.imYfunc udm.imYself

Description documentation string met%od name as a string class %ic% met%od is associated it% function o(4ect for met%od 1see U&/s2 associated instance if (ound* None if un(ound
243 Sree Sakthi Engineering College

'.1#.1.$ C"asses -%e calla(le property of classes allo s instances to (e created. 3Invo+ing3 a class %as t%e effect of creating an instance* (etter +no n as instantiation. '.1#.1.' C"ass instances #yt%on provides t%e YYcallYY12 special met%od for classes %ic% allo s a programmer to create o(4ects 1instances2 %ic% are calla(le. ?y default* t%e YYcallYY12 met%od is not implemented* meaning t%at most instances are not calla(le. '.1#.# Code ObCects $ode o(4ects represent byte'compiled e'ecuta(le #yt%on code* or bytecode. -%e difference (et een a code o(4ect and a function o(4ect is t%at t%e function o(4ect contains an e'plicit reference to t%e function0s glo(als 1t%e module in %ic% it as defined2* %ile a code o(4ect contains no conte'tK also t%e default argument values are stored in t%e function o(4ect* not in t%e code o(4ect 1(ecause t%ey represent values calculated at run)time2. Unli+e function o(4ects* code o(4ects are immuta(le and contain no references 1directly or indirectly2 to muta(le o(4ects. $ode o(4ects are used (y t%e implementation to represent ccpseudo)compiled00 e'ecuta(le #yt%on code suc% as a function (ody. -%ey differ from function o(4ects (ecause t%ey don0t contain a reference to t%eir glo(al e'ecution environment. $ode o(4ects are returned (y t%e (uilt) in compile12 function and can (e e'tracted from function o(4ects t%roug% t%eir funcYcode attri(ute. A code o(4ect can (e e'ecuted or evaluated (y passing it 1instead of a source string2 to t%e e'ec statement or t%e (uilt)in eval12 function. '.1#.$ 0=ecutab"e ObCect State-ents and 5ui"t8in Functions #yt%on provides a num(er of (uilt)in functions supporting calla(les and e'ecuta(le o(4ects* including t%e e=ec statement. 5ui"t8in Function or State-ent calla(le1obC2 compile1strin(? fi"e? Description determines if obC is calla(leK returns 6 if so* : ot%er ise creates a code o(4ect from strin( of type t)peJ
244 Sree Sakthi Engineering College

t)pe2

fi"e is %ere t%e code originates from 1usually set to A2 evaluates obC? %ic% is eit%er a e'pression compiled into a code o(4ect or a string e'pressionK glo(al andCor local namespace dictionaries may also (e provided* ot%er ise* t%e defaults for t%e current environment ill (e used e'ecute obC? a single #yt%on statement or set of statements* eit%er in code o(4ect or string formatK obC may also (e a file o(4ect 1opened to a valid #yt%on script2 e,uivalent to eval1ra Yinput1pro-ptV0022 re,uest intern of strin(

eval1obC? ("oba"sVglo(als12* "oca"sVlocals122

e=ec obC

input1pro-ptV002 intern1strin(2 ca""ab"eRD

calla(le12 is a ?oolean function %ic% determines if an o(4ect type can (e invo+ed via t%e function operator 1 1 2 2. It returns 6 if t%e o(4ect is calla(le and : ot%er ise. Jere are some sample o(4ects and %at calla(le returns for eac% type: PPP calla(le1dir2 S (uilt)in function 6 PPP calla(le162 S integer : PPP def foo12: pass d PPP calla(le1foo2 S user)defined function
245 Sree Sakthi Engineering College

6 PPP calla(le10(ar02 S string : PPP c"ass $: pass d PPP calla(le1$2 S class 6 Co-pi"erRD $ompile t%e source into a code or AS- o(4ect. $ode o(4ects can (e e'ecuted (y an e'ec statement or evaluated (y a call to eval12. source can eit%er (e a string or an AS- o(4ect. Gefer to t%e ast module documentation for information on %o to or+ it% AS- o(4ects. -%e filename argument s%ould give t%e file from -%e mode argument specifies %ic% t%e code as readK pass some recogni.a(le value if it asnMt read from a file 10TstringP0 is commonly used2. %at +ind of code must (e compiledK it can (e 0e'ec0 if source consists of a se,uence of statements* 0eval0 if it consists of a single e'pression* or 0single0 if it consists of a single interactive statement 1in t%e latter case* e'pression statements t%at evaluate to somet%ing ot%er t%an None ill (e printed2. -%e optional arguments flags and dontYin%erit control %ic% future affect t%e compilation of source. If neit%er is present 1or (ot% are .ero2 t%e code is compiled it% t%ose future statements t%at are in effect in t%e code t%at is calling compile. If t%e flags argument is given and dontYin%erit is not 1or is .ero2 t%en t%e future statements specified (y t%e flags argument are used in addition to t%ose t%at ould (e used any ay. If dontYin%erit is a non).ero integer t%en t%e %ic% can (e (it ise OGed toget%er to specify flags argument is it t%e future statements in effect around t%e call to compile are ignored. /uture statements are specified (y (its multiple statements. -%e (it field re,uired to specify a given feature can (e found as t%e compilerYflag attri(ute on t%e Y/eature instance in t%e YYfutureYY module. -%is function raises Synta'@rror if t%e compiled source is invalid* and -ype@rror if t%e source contains null (ytes.
246 Sree Sakthi Engineering College

Note@5%en compiling a string

it% multi)line code in 0single0 or 0eval0 mode* input must (e

terminated (y at least one ne line c%aracter. -%is is to facilitate detection of incomplete and complete statements in t%e code module. e%a"RD -%e arguments are a string and optional glo(als and locals. If provided* glo(als must (e a dictionary. If provided* locals can (e any mapping o(4ect. -%e e'pression argument is parsed and evaluated as a #yt%on e'pression 1tec%nically spea+ing* a condition list2 using t%e glo(als and locals dictionaries as glo(al and local namespace. If t%e glo(als dictionary is present and lac+s eYY(uiltinsYYM* t%e current glo(als are copied into glo(als (efore e'pression is parsed. -%is means t%at e'pression normally %as full access to t%e standard YY(uiltinYY module and restricted environments are propagated. If t%e locals dictionary is omitted it defaults to t%e glo(als dictionary. If (ot% dictionaries are omitted* t%e e'pression is e'ecuted in t%e environment PPP ' V 6 PPP print eval10'I602 7 -%is function can also (e used to e'ecute ar(itrary code o(4ects 1suc% as t%ose created (y compile122. In t%is case pass a code o(4ect instead of a string. If t%e code o(4ect %as (een compiled it% 0e'ec0 as t%e mode argument* eval12es return value ill (e None. %ere eval12 is called. -%e return value is t%e result of t%e evaluated e'pression. Synta' errors are reported as e'ceptions. @'ample:

247 Sree Sakthi Engineering College

UNIT K #erl (ac+grounder #erl overvie

!0R2 #erl parsing rules ]aria(les and &ata

Statements and $ontrol structures Su(routines* #ac+ages* and "odules) 5or+ing it% /iles &ata "anipulation. What is Perl? #erl is a programming language. #erl stands for #ractical Geport and @'traction Language. 8ou0ll notice people refer to 0perl0 and 3#erl3. 3#erl3 is t%e programming language as a %ole %ereas 0perl0 is t%e name of t%e core e'ecuta(le. -%ere is no language called 3#erl<3 )) t%at 4ust means 3#erl version <3. ]ersions of #erl prior to < are very old and very unsupported. Some of #erl0s many strengt%s are:

Speed of de%e"op-ent. 8ou edit a te't file* and 4ust run it. 8ou can develop programs very ,uic+ly li+e t%is. No separate compiler needed. I find #erl runs a program ,uic+er t%an Lava* let alone compare t%e complete modify)compile)run)o%)no)forgot)t%at) semicolon se,uence.
248 Sree Sakthi Engineering College

!ower. #erl0s regular e'pressions are some of t%e (est availa(le. 8ou can o(4ects* soc+ets...everyt%ing a systems administrator could standard distri(ution. Add t%e &on0t e,uate scripting languages it% toy languages.

or+

it%

ant. And t%at0s 4ust t%e

ealt% of modules availa(le on $#AN and you %ave it all. rite a

Usuabi"it). All t%at po er and capa(ility can (e learnt in easy stages. If you can

(atc% file you can program #erl. 8ou don0t %ave to learn o(4ect oriented programming* (ut you can rite OO programs in #erl. If autoincrementing non)e'istent varia(les scares you* ma+e perl refuse to let you. -%ere is al ays more t%an one ay to do it in #erl. 8ou decide your style of programming* and #erl ill accommodate you.

!ortabi"it). On t%e Super%ig% ay to t%e #orta(ility #anacea* #erl0s #orsc%e po ers past Lava0s 4aded 4alopy. "any people develop #erl scripts on N-* or 5inD<* t%en 4ust /-# t%em to a Uni' server %ere t%ey run. No modification necessary.

0ditin( too"s 8ou don0t need t%e latest Integrated &evelopment @nvironment for #erl. 8ou can develop #erl scripts it% any te't editor. Notepad* vi* "S 5ord DE* or even direct off t%e console. Of course* you can ma+e t%ings easy and use one of t%e many free are or s%are are programmer0s file editors.

!rice. 8es* : guilders* pounds* dmar+s* dollars or %atever. And t%e peer to peer support is also free* and often far (etter t%an you0d ever get (y paying some company to ans er t%e p%one and tell you to do %at you 4ust tried several times already* t%en loo+ up t%e same reference (oo+s you already o n.

What can I do with Perl ? Lust t o popular e'amples : The Internet Go surf. Notice %o many e(sites %ave dynamic pages it% .pl or similar as t%e

filename e'tensionA -%at0s #erl. It is t%e most popular language for $GI programming for many reasons* most of %ic% are mentioned a(ove. In fact* t%ere are a great many more dynamic pages ritten it% perl t%at may not %ave a .pl e'tension. If you code in Active Server #ages* t%en you
249 Sree Sakthi Engineering College

s%ould try using ActiveState0s #erlScript. [uite fran+ly* coding in #erlScript rat%er t%an

]?Script or LScript is li+e driving a car as opposed to riding a (icycle. #erl po ers a good deal of t%e Internet. S)ste-s *d-inistration If you are a Uni' sysadmin you0ll +no a(out sed* a + and s%ell scripts. #erl can do

everyt%ing t%ey can do and far more (esides. /urt%ermore* #erl does it muc% more efficiently and porta(ly. &on0t ta+e my ord for it* as+ around. If you are an N- sysadmin* c%ances are you aren0t used to programming. In t%e advantages of #erl may not (e clear. &o you need itA Is it ort% itA After you read t%is tutorial you ill +no more t%an enoug% to start using #erl productively. 8ou really need very little +no ledge to save time. Imagine driving a car for years* t%en realising it %as five gears* not four. -%at0s t%e sort of improvement learning #erl means to your daily sysadminery. 5%en you are proficient* you find t%e difference li+e realising t%e same car %as a reverse gear and you don0t %ave to pus% it (ac+ ards. #erl means you can (e la.ier. La.y sysadmins are good sysadmins* as I +eep telling my (oss. A fe e'amples of %o I use #erl to ease N- sysadmin life:

%ic% case*

User account creation. If you %ave a te't file

it% t%e user0s names in it* t%at is all you

need. $reate usernames automatically* generate a uni,ue pass ord for eac% one and create t%e account* plus create and s%are t%e %ome directory* and set t%e permissions.

0%ent "o( -un(in(. N- %as great @vent Logging. Not so great @vent Geading. 8ou can use #erl to create reports on t%e event logs from multiple N- servers. *n)thin( e"se t%at you ould %ave used a (atc% file for* or is%ed t%at you could

automate some%o . No you can. ,.1 !er" 5ac&(rounder ,.1.1 Kersions and Na-in( Con%entions (ariables
o o

single ord: atom* c%ain multi ord: atomName* centralAtomName


250 Sree Sakthi Engineering College

constants: 6*8IJ*<*+'><(*>$ or *+'><(*>$<6*8IJ** *+'><(*>$<6,$+*

#erl is not type)safe and t%is can cause confusion and errors. Use a limited prefi' notation for suc% common (asic types as array* %as%* /ileJandle.
o o o o

array refs 10a0 prefi'2: aAtoms* a$%ains %as% refs 10%0 prefi'2: %Names7#laces* %$%ains /ileJandle o(4ects 10f%0 prefi'2: f%In* f%Out* f%#d( or 13ist3Vinput stream* 3ost3Voutput stream2: ostId1* ist>sa

"unctions
o o

single ord: -rim12 multi ord: ' en=iles=or%eading()

#o$ules &pac)ages that are not classes'


o o

single ord: Assert multi ord: =ile&oJel er

Classes As for modules (ut it% 0$0 prefi': 6Sto wat/h* 6LindowIanel* Id1::6%esidue *nstance metho$s
o o o

pu(lic met%od: plot12* get$olour12* classifyJetGroups12 private met%od: Yplot12* Yget$olour12* YclassifyJetGroups12 accessor met%ods same as Lava?eans: getIro ertC()? setIro ertC()?
isIro ertC()

,.1.1.1 !er"? per" or !eR" -%ere is also a certain amount of confusion regarding t%e capitali.ation of #erl. S%ould it (e ritten #erl or perlA Larry 5all no uses X#erlF to signify t%e language proper and XperlF to signify t%e implementation of t%e language. ,.1.1.# !er" >istor) Kersion #erl : Date Kersion Detai"s Introduced #erl to Larry 5allMs office associates
251 Sree Sakthi Engineering College

#erl 6 #erl 7 #erl = #erl >

Lan 6D99 Lun 6D99 Oct 6D9D "ar 6DD6

Introduced #erl to t%e orld Introduced Jarry SpencerMs regular e'pression pac+age Introduced t%e a(ility to %andle (inary data Introduced t%e first X$amelF (oo+ 1#rogramming #erl* (y Larry 5all* -om $%ristiansen* and Gandal L Sc% art.K OMGeilly H Associates2. -%e (oo+ drove t%e name c%ange* 4ust so it could refer to #erl >* instead of #erl =.

#erl >.:=B #erl < #erl <.::<Y:7 #erl <.::<Y:= #erl <.B

/e( 6DD= Oct 6DD> Aug 6DD9 "ar 6DDD "ar 7:::

-%e last sta(le release of #erl > -%e first sta(le release of #erl <* %ic% introduced a num(er of ne features and a complete re rite. -%e ne't ma4or sta(le release -%e last sta(le release (efore <.B Introduced unified for& support* (etter t%reading* an updated #erl compiler* and t%e our +ey ord

,.1.#4ain !er" Features ,.1.#.1 !er" Is Free #erlMs source code is open and free any(ody can do nload t%e $ source t%at constitutes a #erl interpreter. /urt%ermore* you can easily e'tend t%e core functionality of #erl (ot% it%in t%e realms of t%e interpreted language and (y modifying t%e #erl source code. ,.1.#.# !er" Is Si-p"e to 2earn? Concise? and 0as) to Read It %as a synta' similar to $ and s%ell script* among ot%ers* (ut format. "ost programs are ,uic+er to it% a less restrictive rite in #erl (ecause of its use of (uilt)in functions and a

%uge standard and contri(uted li(rary. "ost programs are also ,uic+er to e'ecute t%an ot%er languages (ecause of #erlMs internal arc%itecture. ,.1.#.$ !er" Is Fast $ompared to most scripting languages* t%is ma+es e'ecution almost as fast as compiled $ code. ?ut* (ecause t%e code is still interpreted* t%ere is no compilation process* and applications can (e ritten and edited muc% faster t%an it% ot%er languages* it%out any of t%e performance pro(lems normally associated it% an interpreted language.
252 Sree Sakthi Engineering College

,.1.#.' !er" Is 0=tensib"e 8ou can rite #erl)(ased pac+ages and modules t%at e'tend t%e functionality of t%e language. 8ou can also call e'ternal $ code directly from #erl to e'tend t%e functionality. ,.1.#. , !er" >as F"e=ib"e Data T)pes 8ou can create simple varia(les t%at contain te't or num(ers* and #erl ill treat t%e varia(le data accordingly at t%e time it is used. ,.1.#./ !er" Is ObCect Oriented #erl supports all of t%e o(4ect)oriented featuresain%eritance* polymorp%ism* and encapsulation. ,.1.#.1 !er" Is Co""aborati%e -%ere is a %uge net or+ of #erl programmers orld ide. "ost programmers supply* and use* t%e modules and scripts availa(le via $#AN* t%e $ompre%ensive #erl Arc%ive Net or+ ,.1.$ Co-pi"er or Interpreter Co-pi"er A program t%at decodes instructions ritten in a %ig%er order language and produces an assem(ly language program. A compiler t%at generates mac%ine language for a different type of computer t%an t%e one t%e compiler is running in. Interpreter In computing* an interpreter is a computer program t%at reads t%e source code of anot%er computer program and e'ecutes t%at program. A program t%at translates and e'ecutes source language statements one line at a time. Difference between Co-pi"er and Interpreter A compiler first ta+es in t%e entire program* c%ec+s for errors* compiles it and t%en e'ecutes it. 5%ereas* an interpreter does t%is line (y line* so it ta+es one line* c%ec+s it for errors and t%en e'ecutes it. @'ample of $ompiler ) Lava @'ample of Interpreter #J#
253 Sree Sakthi Engineering College

!er" is interpreter or co-pi"er Neit%er* and (ot%. #erl is a scripting language. -%ere is a tool* called perl* intended to run programs ritten in t%e perl language. 3$ompiled3 languages are ones li+e $ and $II* %ere you %ave to ta+e t%e source code* compile it into an e'ecuta(le file* and -J@N run it. 3Interpreted3 languages* li+e #erl* #J#* and Gu(y* are ones %ic% do NO- re,uire pre) compiling. -%ey are generally compiled on)t%e)fly 1 %ic% is %at t%e perl command)line tool does2 into opcodes* and t%en run. So* #erl is an interpreted language (ecause a tool reads t%e source code and immediately runs it. #erl is a compiler (ecause it %as to compile t%at source code (efore it can (e run %ile it0s (eing interpreted. ,.1.' Si-i"ar !ro(ra--in( 2an(ua(es -%ere are many programming languages in use today* eac% of %ic% placing its emp%asis on certain application domains and features. ,.1.'.1 Uni= She""s Uni' uses s%ells to accept commands given (y t%e user* t%ere are ,uite a fe different s%ells availa(le. -%e most commonly used s%ells are SJ1?ourne SJell2 $SJ1$ SJell2 and !SJ1!orn SJell2* most of t%e ot%er s%ells you encounter ill (e variants of t%ese s%ells and ill s%are t%e same synta'* !SJ is (ased on SJ and so is ?ASJ1?ourne again s%ell2. -$SJ 1@'tended $ SJell2 is (ased on $SJ. -%e various s%ells all %ave (uilt in functions automated in order to ma+e life easier for t%e user. ,.1.'.# Tc" -cl 1pronounced -ic+le2 is a general purpose programming language originally intended to (e em(edded in ot%er applications as a configuration and e'tension language. -%e success of one its most important em(eddings* t%e -+ tool+it for t%e X 5indo s System* %as resulted in -cl and -+ toget%er (eing most %eavily used for (uilding grap%ical user interfaces 1GUIs2. It is also
254 Sree Sakthi Engineering College

%ic% allo

for t%e creation of s%ell scripts* %at can (e

t%at is* t%e stringing toget%er of s%ell commands and constructs to automate

%eavily used as a scripting language li+e A +* #erl or Ge''* and 1as @'pect2 is used to script interactive applications 1e.g.* to automate telnet logins to various information vendors2. ,.1.'.$ !)thon #yt%on is a %ig%)level general purpose programming language. ?ecause code is automatically compiled to (yte code and e'ecuted* #yt%on is suita(le for use as a scripting language* 5e( application implementation language* etc. ?ecause #yt%on can (e e'tended in $ and $II* #yt%on can provide t%e speed needed for even compute intensive tas+s. ,.1.'.' La%a Lava is an o(4ect)oriented programming language it% a (uilt)in application programming interface 1A#I2 t%at can %andle grap%ics and user interfaces and t%at can (e used to create applications or applets. ?ecause of its ric% set of A#I0s* similar to "acintos% and 5indo s* and its platform independence* Lava can also (e t%oug%t of as a platform in itself. Lava also %as standard li(raries for doing mat%ematics. ,.1.'., C:CGG #erl is ritten in t%e $ programming language. "any of t%e structures and semantics of #erl and $ are very similar. /or e'ample* (ot% use semicolons as end)of)line terminators. -%ey also s%are t%e same code (loc+ and indentation features. #erl can (e o(4ect oriented li+e $II. ?ot% s%are t%e same a(ilities of in%eritance* polymorp%ism* and encapsulation. ,.1.'./ aw&:(aw& -%ere are some t%ings t%at #erl %as (uilt)in support for t%at a + does not. /or e'ample* a + %as no net or+ soc+et class* and it is largely ignorant of e'ternal files* %en compared to t%e file manipulation and management functions found in #erl. Jo ever* some advantages a + %as over #erl are summari.ed %ere: a + is simpler* and t%e synta' is more structured and regular. Alt%oug% it is gaining acceptance* #erl %as yet to (e included as standard it% many operating systems. A + %as (een supplied it% Uni' almost since it as first released. a + can (e smaller and t%erefore muc% ,uic+er to e'ecute for small programs.
255 Sree Sakthi Engineering College

a + supports more advanced regular e'pressions. 8ou can use a regular e'pression for replacement* and you can searc% te't in su(stitutions.

,.1.'.1 !opu"ar [4)th conceptions\ ItTs on") for the Web #ro(a(ly t%e most famous of t%e myt%s is t%at #erl is a language used* designed* and created e'clusively for developing e()(ased applications. ItTs Not 4aintenance Friend") Any good 1or (ad2 programmer ill tell you t%at any(ody can rite unmaintaina(le code in any language. "any companies and individuals rite maintaina(le programs using #erl. ItTs On") for >ac&ers #erl is used (y a variety of companies* organi.ations* and individuals. @very(ody from programming (eginners t%roug% X%ac+ersF up to multinational corporations use #erl to solve t%eir pro(lems. ItTs a Scriptin( 2an(ua(e In #erl* t%ere is no difference (et een a script and program. "any large programs and pro4ects %ave (een ritten entirely in #erl. ThereTs No Support -%e #erl community is one of t%e largest on t%e Internet* and you s%ould (e a(le to find someone* some %ere* %o can ans er your ,uestions or %elp you it% your pro(lems. *"" !er" !ro(ra-s *re Free Alt%oug% you generally rite and use #erl programs in t%eir native source form* t%is does not mean t%at everyt%ing you rite is free. #erl programs are your o n intellectual property and can (e (oug%t* sold* and licensed 4ust li+e any ot%er program. ThereTs No De%e"op-ent 0n%iron-ent #erl programs are te't (ased* you can use any source)code revision)control system. -%e most popular solution is $]S* or $oncurrent ]ersioning System* %ic% is no supported under Uni'* "acOS and 5indo s.
256 Sree Sakthi Engineering College

!er" Is a .NU !roCect 5%ile t%e GNU pro4ect includes #erl in its distri(utions* t%ere is no suc% t%ing as XGNU #erl.F #erl is not produced or maintained (y GNU and t%e /ree Soft are /oundation. #erl is also made availa(le on a muc% more open license t%an t%e GNU #u(lic License. !er" Is Difficu"t to 2earn ?ecause #erl is similar to a num(er of different languages* it is not only easy to learn (ut also easy to continue learning. Its structure and format is very similar to $* aw&* s%ell script* and* to a greater or lesser e'tent* even ?ASI$. ,.# !er" O%er%iew ,.#.1 Insta""in( and usin( !er" #erl as developed (y Larry 5all. It started out as a scripting language to supplement rn* t%e US@N@- reader. It availa(le on virtually every computer platform. #erl is an interpreted language t%at is optimi.ed for string manipulation* ICO* and system tas+s. It %as (uilt in for most of t%e functions in section 7 of t%e UNIX manuals )) very popular it% sys administrators. it incorporates synta' elements from t%e ?ourne s%ell* cs%* a +* sed* grep* and $. It provides a ,uic+ and effective ay to rite interactive e( applications ,.#.1.1 Writin( a !er" Script #erl scripts are 4ust te't files* so in order to actually X riteF t%e script* all you need to do is create a te't file using your favorite te't editor. Once youMve ritten t%e script* you tell #erl to e'ecute t%e te't file you created. Under Uni'* you ould use N perl myscript.pl and t%e same or+s under 5indo s: $:ZP perl myscript.pl Under "ac OS* you need to drag and drop t%e file onto t%e "ac#erl application. #erl scripts %ave a .pl e'tension* even under "ac OS and Uni'.
257 Sree Sakthi Engineering College

,.#.1.# !er" Under Uni= -%e easiest ay to install #erl modules on Uni' is to use t%e $#AN module. /or e'ample: s%ellP perl )"$#AN )e s%ell cpanP install &?I cpanP install &?&::mys,l -%e &?&::mys,l installation runs a num(er of tests. -%ese tests attempt to connect to t%e local "yS[L server using t%e default user name and pass ord. 1-%e default user name is your login name on Uni'* and O&?$ on 5indo s. -%e default pass ord is Xno pass ord.F2 If you cannot connect to t%e server it% t%ose values 1for e'ample* if your account %as a pass ord2* t%e tests fail. 8ou can use force install &?&::mys,l to ignore t%e failed tests. &?I re,uires t%e &ata::&umper module. It may (e installedK if not* you s%ould install it (efore installing &?I. It is also possi(le to do nload t%e module distri(utions in t%e form of compressed tar arc%ives and (uild t%e modules manually. /or e'ample* to unpac+ and (uild a &?I distri(ution* use a procedure suc% as t%is: 6. Unpac+ t%e distri(ution into t%e current directory: s%ellP gun.ip T &?I)]@GSION.tar.g. _ tar 'vf ) -%is command creates a directory named &?I)]@GSION. 7. $%ange location into t%e top)level directory of t%e unpac+ed distri(ution: s%ellP cd &?I)]@GSION =. ?uild t%e distri(ution and compile everyt%ing: s%ellP perl "a+efile.#L s%ellP ma+e s%ellP ma+e test s%ellP ma+e install -%e ma+e test command is important (ecause it verifies t%at t%e module is or+ing. Note t%at %en you run t%at command during t%e &?&::mys,l installation to e'ercise t%e interface code* t%e "yS[L server must (e running or t%e test fails.
258 Sree Sakthi Engineering College

It is a good idea to re(uild and reinstall t%e &?&::mys,l distri(ution %enever you install a ne release of "yS[L. -%is ensures t%at t%e latest versions of t%e "yS[L client li(raries are installed correctly. ,.#.1.$ !er" Under Windows 6. Log on to t%e 5e( server computer as an administrator. 7. &o nload t%e Active#erl installer from t%e follo ing ActiveState 5e( site: %ttp:CC .activestate.comC 1%ttp:CC .activestate.comC2 =. &ou(le)clic+ t%e *cti%e!er" installer. >. After t%e installer confirms t%e version of Active#erl t%at it is going to (e installed* clic+ Ne=t.
5. If you agree

it% t%e terms of t%e license agreement* clic+ I accept the ter-s in the a(ree-ent* and t%en clic+ Ne=t.

"icense

$lic+ Cance" if you do not accept t%e license agreement. If you do so* you cannot continue t%e installation. B. -o install t%e Ne=t %ole Active#erl distri(ution pac+age 1t%is step is recommended2* clic+ to continue t%e installation. t%e

-%e soft are is installed in t%e default location 1typically $:Z#erl2. E. -o customi.e t%e individual components or to c%ange t%e installation folder* follo instructions t%at appear on t%e screen. 9. 5%en you are prompted to confirm t%e addition features t%at you ant to configure ant to during t%e installation* clic+ any of t%e follo ing settings* and t%en clic+ Ne=t:
o

*dd !er" to the !*T> en%iron-ent %ariab"e : $lic+ t%is setting if you use #erl in a command prompt interpreter.

it%out re,uiring t%e full pat% to t%e #erl ant to allo

Create !er" fi"e e=tension association: $lic+ t%is setting if you e'tension 1.pl2 as a command name.

#erl scripts to (e automatically run %en you use a file t%at %as t%e #erl file name

259 Sree Sakthi Engineering College

Create IIS script -appin( for !er" : $lic+ t%is setting to configure IIS to identify #erl scripts as e'ecuta(le $GI programs according to t%eir file name e'tension. Create IIS script -appin( for !er" IS*!I : $lic+ t%is setting to use #erl scripts as an ISA#I filter.

D. $lic+ Insta"" to start t%e installation process. 6:. After t%e installation %as completed* clic+ Finish. ,.#.# !er" Co-ponents ,.#.#.1 Kariab"es #erl ]aria(les 5or+ing it% t%e tec%ni,ues of %andling t%em are an important part of t%e #erl as designed to %andle %uge amounts of data te't. language. As a language)type script* #erl

it% varia(les is fairly straig%tfor ard given t%at it is not necessary to define and

allocate t%em* so no sop%isticated tec%ni,ues for t%e release of memory occupied (y t%em. As general information* to note t%at t%e names of #erl varia(les contain alp%a(etic c%aracters* num(ers and t%e underscore 1Y2 c%aracter and are case sensitive. A specific language feature is t%at varia(les %ave a non)alp%a(etical prefi' t%at fas%ion some %at cryptic t%e language. -%is* %o ever* presents t%e advantage t%at provides immediate information on t%e type of varia(le and name t%at (egins it% a varia(le* e %ave: scalar varia(les starting it% N array varia(les starting it% U %as%es or associative arrays indicated (y ; -%e N* U and ; c%aracters actually predefine t%e varia(le type in #erl. #erl language also offers some (uilt)in predefined varia(les t%at facilitate and s%orten t%e programming code. ,.#.#.# Operators -%e operators or+ it% num(ers and strings and manipulate data o(4ects called %ic% e need to evaluate.
260 Sree Sakthi Engineering College

%at can (e done

it% it. -%us* according to t%e first

operands. 5e found t%e operators in e'pressions On t%e ot%er side*

e use #erl operators in a certain conte't. 5e %ave t o types of

conte'ts: t%e scalar conte't values. ,.#.#.$ State-ents

%ic% is invo+ed

%en #erl is e'pected to return a single value 1li+e %en #erl is e'pected to return t o or more

t%e addition of t o num(ers2 and t%e list conte't

-%e statements are one of t%e most important topics in t%e #erl language* actually for any programming language. 5e use statements in order to process or evaluate t%e e'pressions. #erl uses t%e values returned (y statements to evaluate or process ot%er statements. A #erl statement ends t%at t%e statement it% t%e semicolon c%aracter 1K2 %ic% is used to tell interpreter as complete. 8ou can put one or more #erl statements on t%e same line of a

#erl script or continue a statement on several lines. ,.#.#.' Subroutines RFunctionsD Definition@ Subroutine RFunctionD is a (loc+ of source code purpose. *d%anta(es@ It reduces t%e $omple'ity in a program (y reducing t%e code. It also reduces t%e -ime to run a program.In ot%er ay*ItMs directly proportional to $omple'ity. ItMs easy to find)out t%e errors due to t%e (loc+s made as function definition outside t%e main function. ,.#.#., 4odu"es A !er" -odu"e is a discrete component of soft are for t%e #erl programming language. -ec%nically* it is a particular set of conventions for using #erl0s pac+age mec%anism t%at %as (ecome universally adopted. A module defines its source code to (e in a package 1muc% li+e a Lava pac+age2* t%e #erl mec%anism for defining namespaces* e.g. 1/& or -et223(P or 4.522ParserK t%e file structure mirrors t%e namespace structure 1e.g. t%e source code for -et223(P is in -et/3(P.pm2. /urt%ermore* a module is t%e #erl e,uivalent of t%e class employed.
261 Sree Sakthi Engineering College

%ic% does one or some tas+s

it% specified

%en o(4ect)oriented programming is

A collection of modules*

it% accompanying documentation* (uild scripts* and usually a test

suite* compose a distribution. ,.$ !er" !arsin( Ru"es ,.$.1 The 0=ecution !rocess -%e e'ecution process of perl contains t%e follo ing steps It ta+es ra input* #arses eac% statement and converts it into a series of opcodes* ?uilds a suita(le opcode tree* @'ecutes t%e opcodes it%in a #erl Xvirtual mac%ine.F

It classifies only t o stages -%e parsing stage and t%e @'ecution or run)time stage -%e #erl parser t%in+s a(out all of t%e follo ing %en it loo+s at a source line: 5asic s)nta= -%e core layout* line termination* and so on Co--ents If a comment is included* ignore it Co-ponent identit) Individual terms 1varia(les* functions and numerical and te'tual constants2 are identified 5are words $%aracter strings t%at are not identified as valid terms !recedence Once t%e individual items are identified* t%e parser processes t%e statements according to t%e precedence rules* %ic% apply to all operators and terms Conte=t 5%at is t%e conte't of t%e statement* are e e'pecting a list or scalar* a num(er or a string* and so on. -%is actually %appens during t%e evaluation of individual elements of a line* %ic% is %y e can nest functions suc% as sort* reverse* and +eys into a single statement line
262 Sree Sakthi Engineering College

,.$.# S)nta= and !arsin( Ru"es

2o(ic S)nta= /or logic operations* t%e parser must treat different values* %et%er constant) or varia(le)(ased* as true or false values All of t%ese present some fairly (asic and fundamental rules a(out %o #erl loo+s at an entire script.

,.$.#.1 5asic S)nta= -%e (asic rules govern suc% t%ings as line termination and t%e treatment of %ite space. -%ese (asic rules are Lines must start it% a to+en t%at does not e'pect a left operandafor e'ample* V DDK is invalid* (ecause t%e V operator e'pects to see a valid lvalue on t%e left side of t%e e'pression. As a general rule* functions and varia(les are t%e primary to+en in a line* it% some e'ceptions. Lines must (e terminated it% a semicolon* e'cept %en itMs t%e last line of a (loc+* %ere t%e semicolon can (e omitted. /or e'ample: print 3JelloZn3 is perfectly legal as a single)line script. Since itMs t%e last line of a (loc+* it doesnMt re,uire any semicolon* (ut print 3Jello 3 print 35orldZn3 ill cause a fault. If you split a line it%in a ,uoted string* t%en t%e line termination (ecomes part of t%e string. 5%ite space is only re,uired (et een to+ens t%at ould ot%er ise (e confusing* so spaces* ta(s* ne lines* and comments 1 %ic% #erl treats as %ite space2 are ignored. -%e line su( menu^print3menu3` or+s as it ould if it ere more neatly spaced. Lines may (e split at any point* providing t%e split is logically (et een t o
263 Sree Sakthi Engineering College

to+ens. -%e follo ing is perfectly legal: print 3%ello3 * 3 orld3K All of t%e preceding are e'amples of t%e core rules for e'ecuting a script. ,.$.#.# Co--ents J-"L* LavaScript* and SSI all %ave comment tags. #@GL follo s t%e trend and also allo s you to enter comment areas. -%is is great considering some scripts can (ecome rat%er indept%. Javing a couple comment lines greatly %elps during editing and documenting. -o comment a line out in #@GL* t%e S sym(ol is used. S -%is line is commented out. S 5e can descri(e %at t%e ne't part of t%e script does. S And so fort% and so on. -%e reason (e%ind using comments is usually to %elp in future editing. It0s (est to enter in descriptive Good : S calculate a cost)of)living ad4ustement and S raise t%e emplyee0s salrary (y t%at amount: Nsalary IV Nsalary W NcolYpercentageK ?ad : S Increment salary (y salary times colYpercentage: Nsalary IV Nsalary W NcolYpercentageK ,.$.#.$ Co-ponent Identit) 5%en #erl fails to identify an item as one of t%e predefined operators* it treats t%e c%aracter se,uence as a Xterm.F -erms are core parts of t%e #erl language and include
264 Sree Sakthi Engineering College

comments

rat%er

t%an

general

unclear

ones.

varia(les* functions* and ,uotes. -%e term)recognition system uses t%ese rules: ]aria(les can start it% a letter* num(er* or underscore* providing t%ey follo a suita(le varia(le c%aracter* suc% as N* U* or ;. ]aria(les t%at start it% a letter or underscore can contain any furt%er com(ination of letters* num(ers* and underscore c%aracters. ]aria(les t%at start it% a num(er can only consist of furt%er num(ersa(e ary of using varia(le names starting it% digits. -%e varia(les suc% as N: t%roug% to ND are used for group matc%es in regular e'pressions. Su(routines can only start it% an underscore or letter* (ut can t%en contain any com(ination of letters* num(ers* and underscore c%aracters. $ase is significantaN]AG* N]ar* and Nvar are all different varia(les. @ac% of t%e t%ree main varia(le types %ave t%eir o n name spaceaNvar* Uvar* and ;var are all separate varia(les. /ile%andles s%ould use all uppercase c%aractersat%is is only a convention* not a rule* (ut it is useful for identification purposes. Once t%e term %as (een e'tracted using t%ese rules* itMs compared against #erlMs internal sym(ol ta(le and t%e sym(ol ta(le of t%e current pac+age. [uotes and constants are also identified and eit%er resolved or tagged at t%is stage as (eing (are values. ,.$.#.' Operators and !recedence *rith-etic Operators -%e follo ing are t%e arit%metic operators in #erl. Operator I ) &escription Addition operator Su(traction operator
265 Sree Sakthi Engineering College

W C ; WW respectively.

"ultiplication operator &ivision operator "odulus operator @'ponentiation operator

-%e operators I* )* W* C ta+e t o operands and return t%e sum* difference* product and ,uotient #erl does an floating point division not an integral division. -o get t%e integral ,uotient one %as to use int12 function. Say if you divide 3int1<C723 t%e result t%e code (elo . 0=a-p"e@ Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K Nnum V < C 7K print int1NnumI:.<2* 3Zn3K Resu"t@ = 8ou may t%in+ of using modulus operator %ic% %as got some issues. So it0s used only if (ot% t%e operands are positive. Not 4ust t%at floating point num(ers are coerced to integers. 0=a-p"e@ Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K Na V 97K N( V 7=.BK Nmod V Na ; 9:K Nmod6 V N( ; 76K print 3-%e modulus of positive num(ers:Nmod3K print 3T(rP3K print 3-%e modulus of floating num(ers:Nmod63K Resu"t@
266 Sree Sakthi Engineering College

ill (e 7* to get t%e e'act result use

-%e modulus of positive num(ers:7 -%e modulus of floating num(ers:7 *ssi(n-ent Operator Operator V IV )V WV CV ;V WWV @veryone +no s %o 0=a-p"e@ Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K Na V <:K Na IV <:K print 3]alue of a using addition operator: Na Zn3K print 3T(rP3K Na ;V 9K print 3]alue of a using modulus*assign operator: Na Zn3K Resu"t@ ]alue of a using addition operator: 6:: ]alue of a using mod*assign operator: > -%e a(ove statement is e,uivalent to 3NaVNaI<:3* t%us displaying t%e result 6::. In t%e same ay* t%e or+ing of modulus assignment operator is s%o n to display t%e remainder as 3NaVNa ;93 e,ual to >.
267 Sree Sakthi Engineering College

/unction Normal Assignment Add and Assign Su(tract and Assign "ultiply and Assign &ivide and Assign "odulus and Assign @'ponent and Assign to use t%e assignment operator 1V2. -%ere are ot%er operators* %en used

it% 3V3 gives a different result.

Incre-ent:Decre-ent Operators -%e follo ing are t%e auto increment* decrement operators in #erl. Operator II )) &escription Autoincrement operator Autodecrement operator value is returned eg:

-%e usage of auto increment operators are same as in $ Language. In prefi' decrementCincrement first t%e value is increased or decreased t%en t%e ne 3IINa3* 3))Na3. -%e vice versa of t%e a(ove* is post decrementCincrement operators. /irst t%e old value is returned t%en incremented or decremented to give t%e result. eg: 3NaII3* 3Na))3 Co-parison Operator Operator VV bV T P TV PV 0=a-p"e@ >V> or > e, > S returns -GU@ <bV> or < ne > S returns -GU@ <T> or < lt > S returns /ALS@ <P> or < gt > S returns -GU@ <TV> or < le > S returns /ALS@ <PV> or < ge > S returns -GU@ In t%e a(ove statements 3TV* PV3 returns true even if (ot% t%e values are same.
268 Sree Sakthi Engineering College

/unction e, ne lt gt le ge @,ual to Operator Not @,ual to Operator Less t%an Operator Greater t%an Operator Lesst%an or @,ual to Operator Greater t%an or @,ual to Operator

0=a-p"e@ Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K NaV6K N(V<K if 1NaVVN(2 ^ print 3?ot% t%e num(ers are @,ual3K ` else ^ print 3-%e num(ers are not e,ual3K ` Resu"t@ -%e num(ers are not e,ual In t%e a(ove code e 4ust compared t o values to display t%e appropriate results. 2o(ica" Operators -%e follo ing are t%e Logical Operators used in #erl. Operator __ b 0=a-p"e@ Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K NaV6K
269 Sree Sakthi Engineering College

/unction logical dis4unction of t%e t o surrounding e'pressions

HH and logical con4unction of t%e t o surrounding e'pressions or not returns t%e logical negation of t%e e'pression to its rig%t

N(V<K if1 1NaTN(2HH1N(PNa22 ^ print 3$ondition is true3K ` else ^ print 3$ondition is /alse3K ` Resu"t@ $ondition is true In t%e a(ove e'ample* t%e varia(les are compared it% t o conditions 6T< and <P6* so t%e result ould give 3$ondition is -rue3 as (ot% t%e conditions are satisfied. 5itwise Operators

Operator TT PP H _ f O

/unction ?inary s%ift left ?inary s%ift rig%t ?it ise AN& ?it ise OG ?it ise XOG ?it ise NO-

-%e (asic criterias for t%e (it ise s%ift operators is t%at t%e operands s%ould (e numerals* (ut t%ese are represented as (inary internally. 5itwise Shift Ri(ht & 2eft@ -%e (it ise s%ift rig%t operator s%ifts t%e specified (its to t%e rig%t or left. /irst 0=a-p"e@
270 Sree Sakthi Engineering College

e convert (ot%

operands to (inary t%en s%ift (its to rig%t or left.-%e (inary digits e,uivalent decimal is t%e result.

Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K NaV>:K N(V7K NcK NdK Nc V NaPPN(K print 35inar) Shift Ri(ht@3K print 3T(rP3K printf 3?inary after s%ifting rig%t NaPPN( V ;:=(Zn3* NcK print 3T(rP3K printf 3&ecimal after s%ifting rig%t NaPPN( V ;dZn3* NcK print 3T(rP3K print 35inar) Shift 2eft@3K print 3T(rP3K Nd V NaTTN(K printf 3?inary after s%ifting left NaTTN( V ;:=(Zn3* NdK print 3T(rP3K printf 3&ecimal after s%ifting left NaTTN( V ;dZn3* NdK Resu"t@ ?inary S%ift Gig%t: ?inary after s%ifting rig%t >:PP7 V 6:6: &ecimal after s%ifting rig%t >:PP7 V 6: ?inary S%ift Left: ?inary after s%ifting left >:TT7 V 6:6::::: &ecimal after s%ifting left >:TT7 V 6B: -%e AN& operator is used to compare t o operands* if (ot% (its are 6 it returns 6* ot%er ise it returns :.-%e ot%er (it ise operators %ave t%e same semantics as t%eir logical operator counterparts e'cept t%e trut% value is represented (y 6 and : for true and false respectively.
271 Sree Sakthi Engineering College

-%e OG operator returns true if eit%er one of t%e (its are 6.-%e XOG operator returns true if (ot% t%e operands are different. -%e NO- operator inverts all (its say :0s to 60s and vice versa 0=a-p"e@ Sb $:ZprogramfilesZperlZ(inZperl print 3content)type: te'tC%tmlZnZn3K NaV=K N(VDK NcK NdK NeK Nc V Na H N(K printf 3?inary value of Na H N( V ;=:(T(rP3*NcK printf 3&ecimal @,uivalent of Na H N( V;dT(rP3*NcK Nd V Na _ N(K printf 3?inary value of Na _ N( V ;=:(T(rP3*NdK printf 3&ecimal @,uivalent of Na _ N( V;dT(rP3*NdK Ne V Na f N(K printf 3?inary value of Na f N( V ;=:(T(rP3*NeK printf 3&ecimal @,uivalent of Na f N( V;dT(rP3*NeK Resu"t@ ?inary value of = H D V 6 &ecimal @,uivalent of = H D V6 ?inary value of = _ D V 6:66 &ecimal @,uivalent of = _ D V66 ?inary value of = f D V 6:6: &ecimal @,uivalent of = f D V6:

Operator !recedence
272 Sree Sakthi Engineering College

-%e follo ing ta(le displays t%e Operator #recedence in #erl. *ssociati%it) left left nonassoc rig%t rig%t left left left left nonassoc nonassoc nonassoc left left left left nonassoc rig%t rig%t left nonassoc rig%t left left ,.$.#., 5are Words ?are ords it%in a script are essentially a (ad idea. /irst #erl tries to identify %et%er t%e (are ord is a proper valueaif it can (e resolved to a function it%in t%e sym(ol ta(le* t%en t%e function is calledK ot%er ise itMs treated as a string. -%e script (elo demonstrates t%is ,uite neatly: su( %ello
273 Sree Sakthi Engineering College

Operators -erms and list operators 1left ard2 )P II )) WW b O n I ) 1unary2 VO bO WC;' I). TT PP named unary operators T P TV PV lt gt le ge VV bV TVP e, ne cmp H _f HH __ .. ... A: V IV )V WV etc. 1assignment operators2 * VP List operators 1rig%t ard2 not and or 'or

^ return 0Jello userb0K ` Nmessage V %elloK print 3NmessageZn3K Nmessage V good(yeK print 3NmessageZn3K This outputs Jello userb good(ye If you %ave arnings s itc%ed on* t%en #erl ill arn you if it sees an all)lo ercase (are ord t%at it canMt ot%er ise identify as a term:@N-ALS XUn,uoted string 3good(ye3 may clas% it% future reserved ord at t.pl line 6:.F ,.$.#./ Conte=ts #erl supports a num(er of different conte'ts* ,./.'.1 Sca"ar and 2ist Conte=t -%ere are t o (asic conte'ts scalar and list. -%ese t o conte'ts affect t%e operation of t%e function or operator concerned (y implying t%e accepted value* or value returned. /or e'ample: Nsi.e V UlistK Jere* t%e Nsi.e varia(le is a scalar* and it t%erefore implies scalar conte't on t%e array* %ic% causes it to return t%e array si.e* rat%er t%an t%e array values. $onversely* t%e statement. sort UlistK is evaluated in list conte't* since t%e sort function e'pects a list of values. ,./.'.# Nu-erica" and Strin( Conte=t In a numerical conte't* t%is varia(le returns t%e numerical error num(er of t%e last error t%at occurred* and in a string conte't* t%e associated message. -%e interpreter uses t%is conte't
274 Sree Sakthi Engineering College

as t%e (asis for t%e conversion of values into t%e internal integer* floating point* or string values t%at t%e scalar value is divided into. ,./.'.$ 5oo"ean Conte=t 5oo"ean conte=t is where an e=pression is used so"e") to identif) a true or fa"se %a"ue. See the [2o(ica" Ka"ues\ section? "ater in the chapter? to see how !er" treats indi%idua" %a"ues and constants in a "o(ica" conte=t. ,./.'.' Koid Conte=t ]oid conte't is a special case and is an e'tension of t%e scalar conte't. It identifies areas of t%e code statement DDK ould (e identified as a void conte't* since introducing a constant at t%is point does not%ing. 8ouMll only (e notified of t%is instance if you %ave arnings s itc%ed on. ,./.'., Interpo"ati%e Conte=t -%e #erl documentation identifies t%e interpolation of varia(les into interpolating S ,uoted values as a separate conte't. -%is is good ay of descri(ing %y some ,uoted (loc+s interpolateat%at is* t%ey are identified as interpolated conte'ta(ut it doesnMt really do t%e process 4ustice. ,.$.#.1 2o(ica" Ka"ues #erlMs ?oolean logic relies on its a(ility to identify different varia(le and constant types as %aving a true or false value. As a general rule* anyt%ing t%at is undefined* empty* or : is ta+en as a false value* %ilst any ot%er value is ta+en as true. -o c%ec+ for t%e undefined value* you can use t%e defined function. Ka"ue Negative : #ositive num(er 2o(ica" Ka"ue num(er -rue /alse -rue
275 Sree Sakthi Engineering College

%ere a constant %as (een introduced (ut never used. At its simplest point* t%e

@mpty string Non)empty string Undefined value @mpty list List it% at least one element ' Kariab"es and Data #erl %as t%ree (uilt in varia(le types: Scalar Array Jas% ,.'.1 5asic Na-in( Ru"es

/alse -rue /alse /alse -rue

-%e (asic rules t%at apply to t%e naming of varia(les it%in #erl: ]aria(le names can start normally (egin it% a letter* a num(er* or an underscore* alt%oug% t%ey

it% a letter and can t%en (e composed of any com(ination of letters* it% a num(er* (ut t%ey must (e entirely composed of t%at num(erK

num(ers* and t%e underscore c%aracter. ]aria(les can start for e'ample* N67= is valid* (ut N6var is not. ]aria(le names t%at start it% anyt%ing ot%er t%an a letter* digit* or underscore are

generally reserved for special use (y #erl 1see XSpecial ]aria(lesF later in t%is c%apter2. ]aria(le names are case sensitiveK Nfoo* N/OO* and NfOo are all separate varia(les as far as #erl is concerned. As an un ritten 1and t%erefore unenforced2 rule* names all in uppercase are constants. All scalar values start it% N* including t%ose accessed from an array of %as%* for e'ample NarrayQ:R or N%as%^+ey`. All array values start All %as%es start it% ;.
276 Sree Sakthi Engineering College

it% U* including arrays or %as%es accessed in slices* for e'ample

UarrayQ=..<*E*DR or U%as%^e(o(M* ealiceM`.

Namespaces are separate for eac% varia(le typeat%e varia(les Nvar* Uvar* and ;var are all different varia(les in t%eir o n rig%t. In situations or ;^%as%`. %ere a varia(le name mig%t get confused it% ot%er data 1suc% as %en em(edded it%in a string2* you can use (races to ,uote t%e name. /or e'ample* N^name`*

,.'.# Sca"ar Kariab"es A scalar represents a single value as follo s: my Nanimal V 3camel3K my Nans er V >7K Jere my is a +ey ord %ic% %as (een e'plained in t%e same section at t%e (ottom. A scalar values can (e strings* integers or floating point num(ers* and #erl values can (e used in various ays: print NanimalK print 3-%e animal is NanimalZn3K print 3-%e s,uare of Nans er is 3* Nans er W Nans er* 3Zn3K -%ere are a num(er of 3magic3 scalars it% names t%at loo+ li+e punctuation or line noise. -%ese special varia(les are used for all +inds of purposes and t%ey ]aria(les sections. -%e only one you need to +no (y certain looping constructs. printK ,.'.$ 2itera"s S prints contents of NY (y default a(out for no ioll (e discussed in Special is NY %ic% is t%e 3default ill automatically convert (et een t%em as re,uired. -%ere is no need to pre)declare your varia(le types. Scalar

varia(le3. It0s used as t%e default argument to a num(er of functions in #erl* and it0s set implicitly

Literal is a value t%at is represented 3as is3 or %ard)coded in your source code. 5%en you see t%e four c%aracters ><.< in programs it really refers to a value of forty)five and a %alf. #erl uses four types of literals. Jere is a ,uic+ glimpse at t%em: Num(ers ) -%is is t%e most (asic data type. Strings ) A string is a series of c%aracters t%at are %andled as one unit. Arrays ) An array is a series of num(ers and strings %andled as a unit. 8ou can also t%in+ of an array as a list.
277 Sree Sakthi Engineering College

Associative Arrays ) -%is is t%e most complicated data type. -%in+ of it as a list in %ic% every value %as an associated loo+up item ,.'.$.1 Nu-eric 2itera"s Numeric literals are simply constant num(ers. Numeric literals are muc% easier to compre%end and use t%an string literals. -%ere are only a fe literals. -%e numeric literal representations t%at #erl users are similar to t%ose used in ot%er languages suc% as $* Ada* and #ascal. -%e follo ing are a fe common e'amples: >7K 67.<K 6:69E=.:::K .::< <@)=K 7=e)6::K 7.=@)DDK 7=eBK 7=Y:::Y:::K S Ucc^-%e num(er >7` S Ucc^A floating point num(er* t elve and a %alf` S Ucc^6:6*9E=` S Ucc^five t%ousandt%s` S Ucc^same num(er as previous line` S Ucc^7= times 6: to t%e po er of )6:: 1very small2` S Ucc^-%e same num(er as t%e line a(oveb` S Ucc^7=*:::*:::` S Ucc^-%e same num(er as line a(ove` S Ucc^-%e underscores are for reada(ility only` (asic ays to e'press numeric

,.'.$.# Strin( 2itera"s Sin("e8Nuoted Single ,uoted are a se,uence of c%aracters t%at (egin and end ant a 0 inside of your string you need to preclude it see %o t%is or+s (elo . 0four0 0canZ0t0 0%iZt%ere0 0(la%ZZ(la%0 S%as four letters in t%e string S%as five c%aracters and represents 3can0t3 S%as eig%t c%aracters and represents3%iZZt%ere3 1one Z in t%e string2 S%as nine c%aracters and represents 3(la%ZZ(la%3 1one Z in t%e string2 Strin(s@ it% a single ,uote. -%ese ,uotes

are not a part of t%e string t%ey 4ust mar+ t%e (eginning and end for t%e #erl interpreter. If you it% a Z li+e t%is Z0 as you0ll see (elo . Let0s

If you ant to put a ne line in a single),uoted string it goes somet%ing li+e t%is
278 Sree Sakthi Engineering College

0line6 line70 S%as eleven c%aracters line6* ne line c%aracter* and t%en line7 strings don0t interpret Zn Strin(s@ as a ne line. Single),uoted Doub"e8Nuoted

&ou(le ,uoted strings act more li+e strings in $ or $II t%e (ac+slas% allo s you to represent control c%aracters. Anot%er nice feature &ou(le)[uoted strings offers is varia(le interpolation t%is su(stitutes t%e value of a varia(le into t%e string. Some e'amples are (elo N ordV3%ello3K NstatementV3N ord orld3K 3Jello 5orldZn3K SN ord (ecomes %ello Svaria(le interpolation* Nstatement (ecomes 3%ello orld3 S3Jello 5orld3 follo ed (y a ne line

So-e of the thin(s )ou can put in a Doub"e8Nuoted Strin( Representation What it 4eans Za ?ell Z( ?ac+space Ze @scape Zf /ormfeed Zn Ne line Zr Geturn Zt -a( ZZ ?ac+slas% Z3 &ou(le ,uote Z::E octal ascii value t%is time ::E or t%e (ell Z':E %e' ascii value t%is time ::E or t%e (ell Zc& any control c%aracter.. %ere it is control)& Zl lo ercase ne't letter Zu uppercase ne't letter ZL lo ercase all letters until Z@ ZU uppercase all letters until Z@ Z[ ?ac+slas% ,uote all nonletters and nonnum(ers until Z@ Z@ Stop ZU ZL or Z[ ,.'.$.$ Nuotes
279 Sree Sakthi Engineering College

It is important to note t%at &OU?L@ ,uotes 3 and SINGL@ ,uotes 0 can %ave a very different effect in #@GL. Single ,uotes are literal. -%ey ill pass on e'actly %at is inside of t%em. $onents are not analy.ed for varia(les. 0=a-p"e @ NmynameV3&avid3K print 0Jello 5orldb "y name is &avid0K print 0Jello 5orldb "y name is Nmyname0K Resu"ts @ Jello 5orldb "y name is &avid Jello 5orldb "y name is Nmyname &ou(le ,uotes are interpolated 1valued or formulated2. ]aria(les ill (e analy.ed for values. 0=a-p"e @ NmynameV3&avid3K print 3Jello 5orldb "y name is &avid3K print 3Jello 5orldb "y name is Nmyname3K Resu"ts @ Jello 5orldb "y name is &avid Jello 5orldb "y name is &avid No as long as my name is &avid 1 %ic% it is2 t%en t%at is all t%ere is to +no a(out ,uotes. One does not c%ec+ for values* and t%e ot%er one does. ,.'.$.' Interpo"ation of *rra) Ka"ues 5%en you em(ed an array into a string* t%e elements of t%e array are included in order separated (y t%e contents of t%e NF special varia(le* %ic% (y default is a space: Ulist V 10%ello0* 0 orld02K print 3UlistZn3K S Outputs 0%ello orld0 #erl ill determine %et%er t%e name you %ave supplied is correct* and itMll raise an error if youMve tried to interpolate an array t%at doesnMt e'ist. -%is can lead to pro(lems: print 3mcUmcslp.com3K In t%is instance* #erl is e'pecting to find an array called Umcslp* and it ill o(viously
280 Sree Sakthi Engineering College

fail (ecause e %avenMt defined suc% an array. Generally* #erl ill arn you of t%is error during compilation and tell you to escape t%e U sign: print 3mcZUmcslp.comUK ,.'.$., >ere Docu-ents #erl offers a convenient ay of printing multiple lines of output t%roug% an interesting ill include t%e t o c%aracters TT follo ed (y a ill use t%e feature +no n as a 3#erl %ere document3. A multiline #erl %ere document or+s li+e t%is: -%e first line of your command

3special3 identifier string* follo ed (y a semi)colon. 1/or my e'ample I identifier string /OO. "ore on t%is s%ortly.2 Ne't* 4ust enter all of t%e lines of output t%at you ant to print.

5%en you are ready to terminate t%e output* put your special identifier string on a line (y itself to end t%e output. to use t%is. Imagine you anted to print a fe lines from t%e

Jere0s an e'ample of %o print TT/OOK

Gettys(urg address from inside of a #erl program: /our score and seven years ago our fat%ers set onto t%is continent 1+eep going %ere ...2 /OO if you put t%is in a #erl program* and t%en run t%e program* t%is 3print TT/OOK3 and 3/OO3* so you ill see t%is output: /our score and seven years ago our fat%ers set onto t%is continent 1+eep going %ere ...2 it ma+es it easy to print multiple lines of output from a #erl program. ,.'.' *rra)s ill print t%e lines in (et een

281 Sree Sakthi Engineering College

An array is 4ust a set of scalars. It0s made up of a list of individual scalars t%at are stored it%in a single varia(le. 8ou can refer to eac% scalar it%in t%at list using a numerical inde'. *rra) Creation@ Array varia(les are prefi'ed t%e , operator. /or e'ample: Uarray V 16* 7* 0Jello02K Uarray V , C-%is is an arrayCK -%e second line uses t%e , CC operator* %ic% returns a list of strings* separating t%e delimited it% t%e U sign and are populated using eit%er parent%eses or

string (y %ite space. In t%is e'ample* t%is leads to a four)element arrayK t%e first element is 0t%is0 and last 1fourt%2 is 0array0. -%is means t%at you can use ne lines it%in t%e specification: Udays V , C"onday -uesday ... SundayCK 5e can also populate an array (y assigning eac% value individually: NarrayQ:R V 0"onday0K ... NarrayQBR V 0Sunday0K 0=tractin( Indi%idua" Indices 5%en e'tracting individual elements from an array* you must prefi' t%e varia(le it% a dollar

sign and t%en append t%e element inde' it%in s,uare (rac+ets after t%e name. /or e'ample: SbCusrC(inCperl Us%ortdays V , C"on -ue 5ed -%u /ri Sat SunCK print Ns%ortdaysQ6RK -%is ill print -ue Array indices start at .ero* so in t%e preceding e'ample e.ve actually printed 3-ue3. 8ou can
282 Sree Sakthi Engineering College

also give a negative inde'.in

%ic% case you select t%e element from t%e end* rat%er t%an t%e

(eginning* of t%e array. -%is means t%at print Ns%ortdaysQ:RK S Outputs "on print Ns%ortdaysQBRK S Outputs Sun print Ns%ortdaysQ)6RK S Also outputs Sun print Ns%ortdaysQ)ERK S Outputs "on Se;uentia" Nu-ber *rra)s #@GL offers a s%ortcut for se,uential num(ers and letters. Gat%er t%an typing out eac% element %en counting to 6:: for e'ample* e can do somet%ing li+e t%is: SbCusrC(inCperl U6: V 16 .. 6:2K U6:: V 16 .. 6::K U6::: V 16:: .. 6:::2K Ua(c V 1a .. .2K print 3U6:3K S #rints num(er starting from 6 to 6: print 3U6::3K S #rints num(er starting from 6 to 6:: print 3U6:::3K S #rints num(er starting from 6 to 6::: print 3Ua(c3K S #rints num(er starting from a to . *rra) Si<e -%e si.e of an array can (e determined using scalar conte't on t%e array ) t%e returned value ill (e t%e num(er of elements in t%e array: Uarray V 16*7*=2K print 3Si.e: 3*scalar Uarray*3Zn3K -%e value returned ill al ays (e t%e p%ysical si.e of t%e array* not t%e num(er of valid elements. 8ou can demonstrate t%is* and t%e difference (et een scalar Uarray and NSarray* using t%is fragment:
283 Sree Sakthi Engineering College

SbCuerC(inCperl Uarray V 16*7*=2K NarrayQ<:R V >K print 3Si.e: 3*scalar Uarray*3Zn3K print 3"a' Inde': 3* NSarray*3Zn3K -%is ill return Si.e: <6 "a' Inde': <: -%ere are only four elements in t%e array t%at contain information* (ut t%e array is <6 elements long* it% a %ig%est inde' of <:. Jere sca"ar function is used to enforce scalar conte't so t%at Uarray can return si.e of t%e array ot%er ise Uarray ill return a lisrt of all t%e elements contacined in it. *ddin( and Re-o%in( 0"e-ents in *rra) Use t%e follo ing functions to addCremove and elements:

pushRD@ adds an element to t%e end of an array. unshiftRD@ adds an element to t%e (eginning of an array. popRD@ removes t%e last element of an array. shiftRD @ removes t%e first element of an array.

5%en adding elements using pus%12 or s%ift12 you must specify t o arguments* first t%e array name and second t%e name of t%e element to add. Gemoving an element it% pop12 or s%ift12 only re,uires t%at you send t%e array as an argument. SbCusrC(inCperl S &efine an array Ucoins V 13[uarter3*3&ime3*3Nic+el32K print 3/irst Statement : Ucoins3K print 3Zn3K
284 Sree Sakthi Engineering College

S Add one element at t%e end of t%e array push1Ucoins* 3#enny32K print 3Second Statement : Ucoins3K print 3Zn3K S Add one element at t%e (eginning of t%e array unshift1Ucoins* 3&ollar32K print 3-%ird Statement : Ucoins3K print 3Zn3K S Gemove one element from t%e last of t%e array. pop1Ucoins2K print 3/ourt% Statement : Ucoins3K print 3Zn3K S Gemove one element from t%e (eginning of t%e array. shift1Ucoins2K print 3/ift% Statement : Ucoins3K print 3Ucoins3K

No t%is ill produce follo ing result /irst Statement : [uarter &ime Nic+el Second Statement : [uarter &ime Nic+el #enny -%ird Statement : &ollar [uarter &ime Nic+el #enny /ourt% Statement : &ollar [uarter &ime Nic+el /ift% Statement : [uarter &ime Nic+el S"icin( *rra) 0"e-ents 8ou can also e'tract a 3slice3 from an array ) t%at is* you can select more t%an one item from an array in order to produce anot%er array.
285 Sree Sakthi Engineering College

U ee+days V Us%ortdaysQ:*6*7*=*>RK -%e specification for a slice must a list of valid indices* eit%er positive or negative* eac% separated (y a comma. /or speed* you can also use t%e .. range operator: U ee+days V Us%ortdaysQ:..>RK Ganges also or+ in lists: U ee+days V Us%ortdaysQ:..7*B*ERK Rep"acin( *rra) 0"e-ents Geplacing elements is possi(le it% t%e splice12 function. Splice12 re,uires a %andful of arguments and t%e formula reads: splice(6array)first'element)sequential"length) new elements) @ssentially* you send #@GL an array to splice* t%en direct it to t%e starting element* count t%roug% %o many elements to replace* and t%en fill in t%e missing elements it% ne information. SbCusrC(inCperl Unums V 16..7:2K splice1Unums* <*<*76..7<2K print 3Unums3K Jere actual replacement (egins after t%e <t% element* starting it% t%e num(er B. /ive elements are t%en replaced from B)6: it% t%e num(ers 76)7< Transfor- Strin(s to *rra)s 5it% t%e split function* it is possi(le to transform a string into an array. -o do t%is simply define an array and set it e,ual to a split function. -%e split function re,uires t o arguments* first t%e c%aracter of %ic% to split and also t%e string varia(le. SbCusrC(inCperl S &efine Strings Nastring V 3Gain)&rops)On)Goses)And)5%is+ers)On)!ittens3K Nnamelist V 3Larry*&avid*Goger*!en*"ic%ael*-om3K

286 Sree Sakthi Engineering College

S Strings are no arrays. Jere 0)0 and 0*0 or+s as delimeter Uarray V split10)0*Nastring2K Unames V split10*0*Nnamelist2K print NarrayQ=RK S -%is ill print Goses print 3Zn3K S -%is is a ne line print NnamesQ>RK S -%is ill print "ic%ael Li+e ise* e can use t%e 4oin12 function to re4oin t%e array elements and form one long* scalar string. SbCusrC(inCperl S &efine Strings Nastring V 3Gain)&rops)On)Goses)And)5%is+ers)On)!ittens3K Nnamelist V 3Larry*&avid*Goger*!en*"ic%ael*-om3K S Strings are no arrays. Jere 0)0 and 0*0 or+s as delimeter Uarray V split10)0*Nastring2K Unames V split10*0*Nnamelist2K Nstring6 V 4oin13*3* Uarray2K Nstring7 V 4oin13)3* Unames2K print Nstring6K print 3Zn3 K print Nstring7K -%is ill produce follo ing result Gain*&rops*On*Goses*And*5%is+ers*On*!ittens
287 Sree Sakthi Engineering College

Larry)&avid)Goger)!en)"ic%ael)-om Sortin( *rra)s -%e sort12 function sorts eac% element of an array according to AS$II Numeric standards. SbCusrC(inCperl S &efine an array Ufoods V , 1pi..a stea+ c%ic+en (urgers2K print 3?efore sorting: UfoodsZn3K S Sort t%is array Ufoods V sort1Ufoods2K print 3After sorting: UfoodsZn3K -%is ill produce follo ing result ?efore sorting: pi..a stea+ c%ic+en (urgers After sorting: (urgers c%ic+en pi..a stea+ #lease note t%at sorting is performed (ased on AS$II Numeric value of t%e perform t%e sort function. The ]Y Specia" Kariab"e ]Y is a special varia(le. -%is particular varia(le is a scalar containing t%e first inde' of all arrays. (ecause #erl arrays %ave .ero)(ased inde'ing* NQ ill almost al ays (e :. ?ut if you set NQ to 6 t%en all your arrays ill use on)(ased inde'ing. It is recommended not to use any ot%er inde'ing ,.'., >ashes Jas%es are an advanced form of array. One of t%e limitations of an array is t%at t%e information contained it%in it can (e difficult to get to. /or e'ample* imagine t%at you %ave a list of people and t%eir ages.
288 Sree Sakthi Engineering College

ords. So t%e

(est option is to first transform every element of t%e array into lo ercase letters and t%en

-%e %as% solves t%is pro(lem very neatly (y allo ing us to access t%at Uages array not (y an inde'* (ut (y a scalar +ey. /or e'ample to use age of different people names as +ey to define a %as%. ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D*2K print 3Gi++e is Nages^Gi++e` years oldZn3K -%is ill produce follo ing result Gi++e is 7D years old Creation of >ash Jas%es are created in one of t o (y)one (asis: Nages^"artin` V 79K In t%e second case* you use a list* %ic% is converted (y ta+ing individual pairs from t%e list: t%e first element of t%e pair is used as t%e +ey* and t%e second* as t%e value. /or e'ample* ;%as% V 10/red0 * 0/lintstone0* 0?arney0* 0Gu((le02K /or clarity* you can use VP as an alias for * to indicate t%e +eyCvalue pairs: ;%as% V 10/red0 VP 0/lintstone0* 0?arney0 VP 0Gu((le02K 0=tractin( Indi%idua" 0"e-ents 8ou can e'tract individual elements from a %as% (y specifying t%e +ey for t%e value t%at you ant it%in (races: print N%as%^/red`K -%is ill print follo ing result /lintstone
289 Sree Sakthi Engineering College

e can use t%ier

ays. In t%e first* you assign a value to a named +ey on a one)

0=tractin( S"ices 8ou can e'tract slices out of a %as% 4ust as you can e'tract slices from an array. 8ou do* %o ever* need to use t%e U prefi' (ecause t%e return value ill (e a list of corresponding values: SbCuerC(inCperl ;%as% V 1)/red VP 0/lintstone0* )?arney VP 0Gu((le02K print 4oin13Zn3*U%as%^)/red*)?arney`2K -%is ill produce follo ing result /lintstone Gu((le Note: Using N%as%^)/red* )?arney` ould return not%ing. 0=tractin( Be)s and Ka"ues 8ou can get a list of all of t%e +eys from a %as% (y using +eys SbCusrC(inCperl ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D2K print 3-%e follo ing are in t%e &?: 3*4oin10* 0*values ;ages2*3Zn3K -%is ill produce follo ing result -%e follo ing are in t%e &?: 7D* 79* =< -%ese can (e useful in loops %en you ant to print all of t%e contents of a %as%: SbCusrC(inCperl ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D2K foreac% N+ey 1;ages2 ^
290 Sree Sakthi Engineering College

print 3N+ey is Nages^N+ey` years oldZn3K ` -%is ill produce follo ing result Gi++e is 7D years old 7D is years old "artin is 79 years old 79 is years old S%aron is =< years old =< is years old -%e pro(lem it% t%is approac% is t%at 1;ages2 returns a list of values. So to resolve t%is pro(lem e %ave each function %ic% ill retun us &e) and %a"ue pair as given (elo SbCusrC(inCperl ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D2K %ile 11N+ey* Nvalue2 V eac% ;ages2 ^ print 3N+ey is Nages^N+ey` years oldZn3K ` -%is ill produce follo ing result Gi++e is 7D years old "artin is 79 years old S%aron is =< years old Chec&in( for 0=istence If you try to access a +eyCvalue pair from a %as% t%at doesn.t e'ist* you.ll normally get t%e undefined value* and if you %ave arnings s itc%ed on* t%en you.ll get a arning generated at run time. 8ou can get around t%is (y using t%e e=ists function* %ic% returns true if t%e named +ey e'ists* irrespective of %at its value mig%t (e:
291 Sree Sakthi Engineering College

SbCusrC(inCperl ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D2K if 1e'ists1Nages^3mo%ammad3`22 ^ print 3mo%ammad if Nages^Nname` years oldZn3K ` else ^ print 3I don0t +no t%e age of mo%ammadZn3K ` -%is ill produce follo ing result I don0t +no t%e age of mo%ammad Sortin(:Orderin( >ashes -%ere is no ay to simply guarantee t%at t%e order in %ic% a list of +eys* values* or +eyCvalue pairs ill al ays (e t%e same. In fact* it0s (est not even to rely on t%e order (et een t o se,uential evaluations: SbCusrC(inCperl print14oin10* 0*+eys ;%as%2*3Zn32K print14oin10* 0*+eys ;%as%2*3Zn32K If you ant to guarantee t%e order* use sort* as* for e'ample: print14oin10* 0*sort +eys ;%as%2*3Zn32K If you are accessing a %as% a num(er of times and ant to use t%e same order* consider creating a single array to %old t%e sorted se,uence* and t%en use t%e array 1 %ic% ill remain in sorted order2 to iterate over t%e %as%. /or e'ample: my Usortorder V sort +eys ;%as%K
292 Sree Sakthi Engineering College

foreac% my N+ey 1Usortorder2 >ash Si<e 8ou get t%e si.e ) t%at is* t%e num(er of elements ) from a %as% (y using scalar conte't on eit%er +eys or values: SbCusrC(inCperl ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D2K print 3Jas% si.e: 3*scalar +eys ;ages*3Zn3K -%is ill produce follo ing result Jas% si.e: = *dd & Re-o%e 0"e-ents in >ashes Adding a ne +eyCvalue pair can (e done it% one line of code using simple assignment operator. ?ut to remove an element from t%e %as% you need to use de"ete function. SbCusrC(inCperl ;ages V 10"artin0 VP 79* 0S%aron0 VP =<* 0Gi++e0 VP 7D2K S Add one more element in t%e %as% Nage^0Lo%n0` V >:K S Gemove one element from t%e %as% delete1 Nage^0S%aron0` 2K ,.'./ 2ists ot%er t%an .ero. The 2ists Lists are really a special type of array ) .essentially* a list is a temporary construct t%at %olds a series of values. -%e list can (e 3%and3 generated using parent%eses and t%e comma operator* Uarray V 16*7*=2K
293 Sree Sakthi Engineering College

or it can (e t%e value returned (y a function or varia(le %en evaluated in list conte't: print 4oin10*0 Uarray2K Jere* t%e Uarray is (eing evaluated in list conte't (ecause t%e 4oin function is e'pecting a list. 4er(in( 2ists Ror *rra)sD ?ecause a list is 4ust a comma)separated se,uence of values* you can com(ine lists toget%er: Unum(ers V 16*=*1>*<*B22K -%e em(edded list 4ust (ecomes part of t%e main list.t%is also means t%at e can com(ine arrays toget%er: Unum(ers V 1Uodd*Ueven2K /unctions t%at return lists can also (e em(edded to produce a single* final list: Unum(ers V 1primes12*s,uares122K Se"ectin( 0"e-ents fro- 2ists -%e list notation is identical to t%at for arrays ) .you can e'tract an element from an array (y appending s,uare (rac+ets to t%e list and giving one or more indices: SbCusrC(inCperl None V 1<*>*=*7*62Q>RK print 3]alue of ZNone is NoneZn3 -%is ill produce foll oing result ]alue of None is 6 Similarly* e can e'tract slices* alt%oug% it%out t%e re,uirement for a leading U c%aracter: SbCusrC(inCperl Une list V 1<*>*=*7*62Q6..=RK print 3value of ne list is Une listZn3K
294 Sree Sakthi Engineering College

-%is ill produce foll oing result value of ne list is > = 7 *rra)s in 2ist Conte=t 5%en accessing an entire array or slice* arrays or+ as listsat%at is Uarray V 16*72K 1Na* N(2 V UarrayK is e,uivalent to 1Na* N(2 V 16* 72K >ashes in 2ist Conte=t In t%e same ay t%at %as%es are essentially populated using a list* if you evaluate a %as% in list conte't* t%en %at you get is a list of +eyCvalue pairs. /or e'ample* my ;%as% V 1/red VP 0/lintstone0* ?arney VP 0Gu((le02K Ulist V ;%as%K print 4oin10* 0*Ulist2K produces ?arney* Gu((le* /red* /lintstone ,.'.1 T)pe("obs -ypeglo(s are immensely useful. -%ey allo us to efficiently create aliases of sym(ols* %ic% is t%e (asis for a very important module called @'porter t%at is used in a large num(er of freely availa(le modules -ypeglo(s can also (e aliased to ordinary references in suc% a ay t%at you don0t %ave to use t%e dereferencing synta'K t%is is not only easier on t%e eye* it is faster too. $losely related to typeglo(s and sym(ol ta(les is t%e su(4ect of dynamic versus le'ical scoping 1using local versus my 2. -%ere are a couple of useful idioms t%at arise from t%ese differences.

295 Sree Sakthi Engineering College

S%mbol table an$ t%peglobs ,.'.3 The defined Function and the Undefined Ka"ue undef@ Undefines t%e value of @X#G. Use on a scalar* list* %as%* function* or typeglo(. Use on a %as% it% a statement suc% as undef N%as%^N+ey`K actually sets t%e value of t%e specified +ey to an undefined value. If you ant to delete t%e element from t%e %as%* use t%e delete function. Syntax undef @X#G undef Example SbCusrC(inCperl ) Nscalar V 6:K Uarrary V 16*72K print 36 ) ]alue of Scalar is NscalarZn3K print 36 ) ]alue of Array is UarrayZn3K undef1 Nscalar 2K undef1 Uarray 2K print 37 ) ]alue of Scalar is NscalarZn3K print 37 ) ]alue of Array is UarrayZn3K

296 Sree Sakthi Engineering College

It ill produce follo ing results: 6 ) ]alue of Scalar is 6: 6 ) ]alue of Array is Use of uninitiali.ed value in concatenation 1.2 or string at test.pl line 6=. 7 ) ]alue of Scalar is 7 ) ]alue of Array is defined@ Geturns true if 0A!R %as a value ot%er t%an t%e undef value* or c%ec+s t%e value of NY if @X#G is not specified. -%is can (e used it% many functions to detect a failure in operation* since t%ey return undef if t%ere as a pro(lem. A simple ?oolean test does not differentiate (et een false* .ero* an empty string* or t%e string .:.* %ic% are all e,ually false. If 0A!R is a function or function reference* t%en it returns true if t%e function %as (een defined. 5%en used it% entire arrays and %as%es* it ill not al ays produce intuitive results. If a %as% element is specified* it returns true if t%e corresponding value %as (een defined* (ut does not determine %et%er t%e specified +ey e'ists in t%e %as%. Return Ka"ue

: if @X#G contains undef 6 if @X#G contains a valid value or reference

Syntax defined @X#G defined 0=a-p"e SbCusrC(inCperl Nvar6 V 3-%is is defined3K if1 defined1Nvar62 2^ print 3Nvar6Zn3K
297 Sree Sakthi Engineering College

` if1 defined1Nvar72 2^ print 3var7 is also definedZn3K `else^ print 3var7 is not definedZn3K ` -%is ill produce follo ing result -%is is defined var7 is not defined ,.'.6 Defau"t Ka"ues ItMs not necessary it%in #erl to initiali.e varia(les it% some default values. #erl automatically creates all scalars as empty 1 it% t%e undefined value2. Lists and %as%es are automatically created empty '.17 Other To&ens -o+en E E2IN0E E E EFI20E E EE!*CB*.0EE EE0NDEE EED*T*EE ]alue -%e current line num(er it%in t%e current file. -%e name of t%e current file. -%e name of t%e current pac+age. If t%ere is no current pac+age* t%en it returns t%e undefined value. Indicates t%e end of t%e script 1or interpreta(le #erl2 it%in a file (efore t%e p%ysical end of file. As for EE0NDEE* e'cept t%at it also indicates t%e start of t%e D*T* file%andle t%at can (e opened it% t%e open* t%erefore allo ing you to em(ed script and data into t%e same script. ,., State-ents and Contro" Structures ,.,.1 Code 5"oc&s A se,uence of statements is called a code (loc+* or simply 4ust a (loc+. A (loc+ of code could (e any of t%e code e'amples t%at e %ave seen t%us far. -%e only difference is* to ma+e t%em a (loc+* e ould surround t%em it% ^`.
298 Sree Sakthi Engineering College

use strictK ^ my NvarK StatementK StatementK StatementK ` Anyt%ing t%at loo+s li+e t%at is a (loc+. ?loc+s are very simple* and are muc% li+e code (loc+s in languages li+e $* $II* and Lava. Jo ever* in #erl* code (loc+s are decoupled from any particular control structure. -%e a(ove code e'ample is a valid piece of #erl code t%at can appear 4ust a(out any %ere in a #erl program. Of course* it is only particularly useful for t%ose functions and structures t%at use (loc+s. ,.,.# Conditiona" State-ents -%e conditional statements are if and un"ess* and t%ey allo you to control t%e e'ecution of your script. -%ere are five different formats for t%e if statement: if 1@X#G2 if 1@X#G2 ?LO$! if 1@X#G2 ?LO$! else ?LO$! if 1@X#G2 ?LO$! elsif 1@X#G2 ?LO$! ... if 1@X#G2 ?LO$! elsif 1@X#G2 ?LO$! ... else ?LO$! S-A-@"@N- if 1@X#G2 -%e first format is classed as a simple statement* since it can (e used at t%e end of anot%er statement it%out re,uiring a (loc+* as in: print 3Jappy ?irt%daybZn3 if 1Ndate VV Ntoday2K In t%is instance* t%e message ill only (e printed if t%e e'pression evaluates to a true value. -%e second format is t%e more familiar conditional statement t%at you may %ave come across in ot%er languages:
299 Sree Sakthi Engineering College

if 1Ndate VV Ntoday2 ^ print 3Jappy ?irt%daybZn3K ` -%is produces t%e same result as t%e previous e'ample. -%e t%ird format allo s for e'ceptions. If t%e e'pression evaluates to true* t%en t%e first (loc+ is e'ecutedK ot%er ise 1else2* t%e second (loc+ is e'ecuted: if 1Ndate VV Ntoday2 ^ print 3Jappy ?irt%daybZn3K ` else ^ print 3Jappy Un(irt%daybZn3K ` -%e fourt% form allo s for additional tests if t%e first e'pression does not return true. -%e elsif can (e repeated an infinite num(er of times to test as many different alternatives as are re,uired: if 1Ndate VV Ntoday2 ^ print 3Jappy ?irt%daybZn3K ` elsif 1Ndate VV Nc%ristmas2 ^ print 3Jappy $%ristmasbZn3K ` -%e fift% form allo s for (ot% additional tests and a final e'ception if all t%e ot%er tests fail: if 1Ndate VV Ntoday2 ^ print 3Jappy ?irt%daybZn3K
300 Sree Sakthi Engineering College

` elsif 1Ndate VV Nc%ristmas2 ^ print 3Jappy $%ristmasbZn3K `else ^ print 3Jappy Un(irt%daybZn3K ` -%e unless statement automatically implies t%e logical opposite of if* so unless t%e 0A!R is true* e'ecute t%e (loc+. -%is means t%at t%e statement print 3Jappy Un(irt%daybZn3 unless 1Ndate VV Ntoday2K is e,uivalent to print 3Jappy Un(irt%daybZn3 if 1Ndate bV Ntoday2K /or e'ample* t%e follo ing is a less elegant solution to t%e preceding if...else. Alt%oug% it ac%ieves t%e same result* e'ample: unless 1Ndate bV Ntoday2 ^ print 3Jappy Un(irt%daybZn3K ` else ^ print 3Jappy ?irt%daybZn3K ` -%e final conditional statement is actually an operator.t%e conditional operator. It is synonymous it% t%e if...else conditional statement (ut is s%orter and more compact. -%e format for t%e operator is: 1e'pression2 A 1statement if true2 : 1statement if false2 /or e'ample* e can emulate t%e previous e'ample as follo s: 1Ndate VV Ntoday2 A print 3Jappy ?.&aybZn3 : print 3Jappy &aybZn3K
301 Sree Sakthi Engineering College

,.,.$ 2oops #erl supports four main loop types: 6. %ile 7. for =. until >. foreac% In eac% case* t%e e'ecution of t%e loop continues until t%e evaluation of t%e supplied e'pression c%anges.

In t%e case of a whi"e loop e'ecution continues %ile t%e e'pression evaluates to true. -%e until loop e'ecutes %ile t%e loop e'pression is false and only stops %en t%e e'pression evaluates to a true value. -%e list forms of t%e for and foreach loop are special cases. -%ey continue until t%e end of t%e supplied list is reac%ed.

,.,.$.1 whi"e 2oops -%e %ile loop %as t%ree forms: %ile @X#GLA?@L %ile 1@X#G2 ?LO$!LA?@L %ile 1@X#G2 ?LO$! continue ?LO$! In first form* t%e e'pression is evaluated first* and t%en t%e statement to %ic% it applies is evaluated. /or e'ample* t%e follo ing line increases t%e value of Nlinecount as long as e continue to read lines from a given file: /or e'ample* t%e follo ing line increases t%e value of Nlinecount as long as e continue to read lines from a given file: NlinecountII %ile 12K -o create a loop t%at e'ecutes statements first* and t%en tests an e'pression* you need to com(ine %ile it% a preceding do ^_ statement. /or e'ample: do ^
302 Sree Sakthi Engineering College

Ncalc IV 1NfactWNivalue2K ` %ile Ncalc T6::K In t%is case* t%e code (loc+ is e'ecuted first* and t%e conditional e'pression is only evaluated at t%e end of eac% loop iteration. -%e second t o forms of t%e %ile loop repeatedly e'ecute t%e code (loc+ as long as t%e result from t%e conditional e'pression is true. /or e'ample* you could re rite t%e preceding e'ample as: %ile1Ncalc T 6::2 ^ Ncalc IV 1NfactWNivalue2K ` ,.,.$.# unti" 2oops -%e inverse of t%e %ile loop is t%e until loop* %ic% evaluates t%e conditional e'pression and reiterates over t%e loop only %en t%e e'pression returns false. Once t%e e'pression returns true* t%e loop ends. In t%e case of a do.until loop* t%e conditional e'pression is only evaluated at t%e end of t%e code (loc+. In an until 1@X#G2 ?LO$! loop* t%e e'pression is evaluated (efore t%e (loc+ e'ecutes. Using an until loop* you could re rite t%e previous e'ample as: do ^ Ncalc IV 1NfactWNivalue2K ` until Ncalc PV 6::K -%is is e,uivalent to do ^ Ncalc IV 1NfactWNivalue2K
303 Sree Sakthi Engineering College

` %ile Ncalc T6::K ,.,.$.$ for 2oops A for loop is (asically a %ile loop it% an additional e'pression used to reevaluate t%e original conditional e'pression. -%e (asic format is: LA?@L for 1@X#GK @X#GK @X#G2 ?LO$! -%e first @X#G is t%e initiali.ation ) t%e value of t%e varia(les (efore t%e loop starts iterating. -%e second is t%e e'pression to (e e'ecuted for eac% iteration of t%e loop as a test. -%e t%ird e'pression is e'ecuted for eac% iteration and s%ould (e a modifier for t%e loop varia(les. -%us* you can rite a loop to iterate 6:: times li+e t%is: for 1NiV:KNiT6::KNiII2 ^ ... ` 8ou can place multiple varia(les into t%e e'pressions using t%e standard list operator 1t%e comma2: for 1NiV:* N4V:KNiT6::KNiII*N4II2 8ou can create an infinite loop li+e t%is: for1KK2 ^ ... ` ,.,.$.' foreach 2oops %e last loop type is t%e foreac% loop* %ic% %as a format li+e t%is: LA?@L foreac% ]AG 1LIS-2 ?LO$! LA?@L foreac% ]AG 1LIS-2 ?LO$! continue ?LO$! Using a for loop* you can iterate t%roug% t%e list using: for 1Ninde'V:KNinde'TVUmont%sKNinde'II2
304 Sree Sakthi Engineering College

^ print 3Nmont%sQNinde'RZn3K ` -%is is messy* (ecause you.re manually selecting t%e individual elements from t%e array and using an additional varia(le* Ninde'* to e'tract t%e information. Using a foreac% loop* you can simplify t%e process: foreac% 1Umont%s2 ^ print 3NYZn3K ` -%e foreac% loop can even (e used to iterate t%roug% a %as%* providing you return t%e list of values or +eys from t%e %as% as t%e list: foreac% N+ey 1+eys ;mont%stonum2 ^ print 3"ont% Nmont%stonum^N+ey` is N+eyZn3K ` ,.,.$., The continue 5"oc& -%e continue (loc+ is e'ecuted immediately after t%e main (loc+ and is primarily used as a met%od for e'ecuting a given statement 1or statements2 for eac% iteration* irrespective of %o t%e current iteration terminated. It is some%o e,uivalent to for loop ^ my Ni V :K %ile 1Ni T6::2 ^ ... ` continue ^ NiIIK `
305 Sree Sakthi Engineering College

` -%is is e,uivalent to for 1my Ni V :K Ni T 6::K NiII2 ^ ... ` ,.,.$./ 2abe"s La(els can (e applied to any (loc+* (ut t%ey ma+e t%e most sense on loops. ?y giving your loop a name* you allo t%e loop control +ey ords to specify %ic% loop t%eir operation s%ould (e applied to. -%e format for a la(eled loop is: LA?@L: loop 1@X#G2 ?LO$! ... /or e'ample* to la(el a for loop: I-@GA-@: for 1my NiV6K NiT6::K NiII2 ^ print 3$ount: NiZn3K ` ,.,.$.1 2oop Contro" -%ere are t%ree loop control +ey ords: ne't* last* and redo. -%e ne=t +ey ord s+ips t%e remainder of t%e code (loc+* forcing t%e loop to proceed to t%e ne't value in t%e loop. /or e'ample: %ile 1T&A-AP2 ^ ne't if CfSCK ` A(ove code ould s+ip lines from t%e file if t%ey started it% a %as% sym(ol. If t%ere is a continue (loc+* it is e'ecuted (efore e'ecution proceeds to t%e ne't iteration of t%e loop. -%e "ast +ey ord ends t%e loop entirely* s+ipping t%e remaining statements in t%e code (loc+* as ell as dropping out of t%e loop. -%e last +ey ord is t%erefore identical to t%e (rea+ +ey ord in $ and S%ellscript. /or e'ample: %ile 12
306 Sree Sakthi Engineering College

^ last if 1Nfound2K ` 5ould e'it t%e loop if t%e value of Nfound as true* %et%er t%e end of t%e file %ad actually (een reac%ed or not. -%e continue (loc+ is not e'ecuted. -%e redo +ey ord ree'ecutes t%e code (loc+ it%out reevaluating t%e conditional statement for t%e loop. -%is s+ips t%e remainder of t%e code (loc+ and also t%e continue (loc+ (efore t%e main code (loc+ is ree'ecuted. /or e'ample* t%e follo ing code ould read t%e ne't line from a file if t%e current line terminates it% a (ac+slas%: %ile1T&A-AP2 ^ if 1sSZZNS2 ^ NY .V T&A-APK redoK ` ` Jere is an e'ample s%o ing %o la(els are used in inner and outer loops OU-@G: %ile1T&A-AP2 ^ c%ompK UlinearrayVsplitK foreac% N ord 1Ulinearray2 ^ ne't OU-@G if 1N ord VO Cne'tCi2 ` ` ,.,.$.3 (oto
307 Sree Sakthi Engineering College

-%ere are t%ree (asic forms: (oto 2*502? (oto 0A!R? and (oto &N*40. In eac% case* e'ecution is moved from t%e current location to t%e destination. In t%e case of goto 2*502* e'ecution stops at t%e current point and resumes at t%e point of t%e la(el specified. -%e (oto &N*40 statement is more comple'. It allo s you to replace t%e currently e'ecuting su(routine it% a call to t%e specified su(routine instead. ,./ Subroutines? !ac&a(es? and 4odu"es ,./.1 Functions Definition@ /unction is a (loc+ of source code %ic% does one or some tas+s it% specified purpose. *d%anta(es@ It reduces t%e $omple'ity in a program (y reducing t%e code. It also reduces t%e -ime to run a program.In ot%er ay*ItMs directly proportional to $omple'ity. ItMs easy to find)out t%e errors due to t%e (loc+s made as function definition outside t%e main function. Su(routines* li+e varia(les* can (e declared and defined. ]arious forms: su( NA"@ su( NA"@ #GO-O su( NA"@ A--GS su( NA"@ #GO-O A--GS %ere as #GO-O #rototype* A--GS Attri(utes @'amples: su( message ^ print 3JellobZn3K `
308 Sree Sakthi Engineering College

-o call t%e su(routine and get a result* add16*72K ,./.1.1 *r(u-ents In perl e do not declare arguments a function ta+es %ile e defining a function* e still may pass arguments to a #erl function. All arguments are passed into a function t%roug% t%e special array UY. -%us* e can send as many arguments as e ant and also function may receive different num(er of arguments. @'ample 6: simple function adds t o num(ers and prints t%e result: su( add ^ Nresult V NYQ:R I NYQ6RK print 3-%e result as: NresultZn3K ` -o call t%e su(routine and get a result* add16*72K @'ample 7: su(myYargs ^ my NiK print 3"y arguments:Zn3K for1NiV:KNiTVNSYKNiII2^ print 3Argument Ni: NYQNiRZn3K ` print 3Zn3K ` my Nname V 3arg one3K my Unames V 10-%is0* 0is0* 0an0* 0array02K myYargs1Nname2K myYargs1Nname* 67=2K myYargs167=* =><* Unames* Nname2K
309 Sree Sakthi Engineering College

$ounting Arguments: If you ant to count t%e num(er of arguments t%at you %ave received* 4ust access t%e UY in a scalar conte't: @'ample: my Ncount V UYK ,./.1.# Return Ka"ues A su(routine is al ays part of some e'pression. -%e value of t%e su(routine invocation is called t%e return value . -%e return value of a su(routine is t%e value of t%e return statement or of t%e last e'pression evaluated in t%e su(routine. /or e'ample* let0s define t%is su(routine: su(sumYofYaYandY( ^ return Na I N(K ` -%e last e'pression evaluated in t%e (ody of t%is is t%e sum of Na and N( * so t%e sum of Na and N( ill (e t%e return value. Jere0s t%at in action: Na V =K N( V >K Nc V sumYofYaYandY(12K S Nc gets E Nd V = W sumYofYaYandY(12K S Nd gets 76 A su(routine can also return a list of values %en evaluated in a list conte't. $onsider t%is su(routine and invocation: su(listYofYaYandY( ^ return1Na*N(2K ` Na V <K
310 Sree Sakthi Engineering College

N( V BK Uc V listYofYaYandY(12K S Uc gets 1<*B2 -%e last e'pression evaluated really means t%e last e'pression evaluated* rat%er t%an t%e last e'pression defined in t%e (ody of t%e su(routine. /or e'ample* t%is su(routine returns Na if Na P: K ot%er ise it returns N( : ,./.1.$ 0rror Notification -%e easiest ay to report an error it%in a su(routine is to return t%e undefined value undef function. undef@ Undefines t%e value of @X#G. Use on a scalar* list* %as%* function* or typeglo(. Use on a %as% it% a statement suc% as undef N%as%^N+ey`K actually sets t%e value of t%e specified +ey to an undefined value. If you ant to delete t%e element from t%e %as%* use t%e delete function. S)nta= undef @X#G undef 0=a-p"e SbCusrC(inCperl ) Nscalar V 6:K Uarrary V 16*72K print 36 ) ]alue of Scalar is NscalarZn3K print 36 ) ]alue of Array is UarrayZn3K undef1 Nscalar 2K undef1 Uarray 2K print 37 ) ]alue of Scalar is NscalarZn3K print 37 ) ]alue of Array is UarrayZn3K

311 Sree Sakthi Engineering College

It ill produce follo ing results: 6 ) ]alue of Scalar is 6: 6 ) ]alue of Array is Use of uninitiali.ed value in concatenation 1.2 or string at test.pl line 6=. 7 ) ]alue of Scalar is 7 ) ]alue of Array is

,./.1.' Conte=t If you rite a #erl program* you refer to lists it% an 3U3 sym(ol in front of t%e list varia(le name. ?ut depending on t%e conte't of %o you rite it* t%e program may interpret it as -%e list contents 1if t%e operation is normal for a list2. -%e lengt% of t%e list 1i.e. t%e element count2 if t%at0s t%e only t%ing t%at ma+es sense. A space separated string it% all t%e items in t%e list 4oined toget%er 1if it0s in dou(le ,uotes2. For e=a-p"e@ Usalad V 13apple3*3(anana3*3c%erry32K NsaladQ=R V 3tomato3K NsaladQ9R V 3fig3K print Usalad.3Zn3K S scalar conte't print 3Usalad.Zn3K S dou(le ,uote conte't wi"" disp"a)@ apple(ananac%errytomatofig D apple (anana c%erry tomato ,./.1., *ttributes Attri(utes allo you to add e'tra semantics to any #erl su(routine or varia(le.$urrently #erl supports only t%ree attri(utes: loc+ed* met%od* and lvalue The "oc&ed *ttribute
312 Sree Sakthi Engineering College

fig.

S Only one t%read is allo ed into t%is function. su(afunc : loc+ed ^ ... ` S Only one t%read is allo ed into t%is function on a given o(4ect. su(afunc : loc+ed met%od ^ ... ` Setting t%e loc+ed attri(ute is meaningful only %en t%e su(routine or met%od is intended to (e called (y multiple t%reads simultaneously. 5%en set on a nonmet%od su(routine* #erl ensures t%at a loc+ is ac,uired on t%e su(routine itself (efore t%at su(routine is entered. 5%en set on a met%od su(routine 1t%at is* one also mar+ed it% t%e met%od attri(ute2* #erl ensures t%at any invocation of it implicitly loc+s its first argument 1t%e o(4ect2 (efore e'ecution. Semantics of t%is loc+ are t%e same as using t%e loc+ operator on t%e su(routine as t%e first statement in t%at routine. The 4ethod attribute@ su(afunc : met%od ^ ... ` $urrently t%is %as only t%e effect of mar+ing t%e su(routine so as not to trigger t%e 3Am(iguous call resolved as $OG@::;s3 arning. 15e may ma+e it mean more someday.2 -%e attri(ute system is user)e'tensi(le* letting you create your o n attri(ute names. -%ese ne attri(utes must (e valid as simple identifier names 1 it%out any punctuation ot%er t%an t%e 3Y3 c%aracter2. -%ey may %ave a parameter list appended* %ic% is currently only c%ec+ed for %et%er its parent%eses nest properly. Jere are e'amples of valid synta' 1even t%oug% t%e attri(utes are un+no n2: su(fnord 1HZ;2 : s itc%16:*foo1E*=22 : e'pensiveK su(plug% 12 : Ugly10Z132 :?adK su('y..y : Y<'< ^ ... ` Jere are e'amples of invalid synta': su(fnord : s itc%16:*foo12K S 12)string not (alanced su(snoid : Ugly10102K su('y..y : <'<K su(plug% : 87::nort%K S 12)string not (alanced S 3<'<3 not a valid identifier S 387::nort%3 not a simple identifier
313 Sree Sakthi Engineering College

su(snurt : foo I (arK

S 3I3 not a colon or space

-%e attri(ute list is passed as a list of constant strings to t%e code t%at associates t%em it% t%e su(routine. @'actly %o t%is or+s 1or doesn0t2 is %ig%ly e'perimental. $%ec+ attri(utes1=2 for current details on attri(ute lists and t%eir manipulation. The "%a"ue *ttribute Using lvalue* a su(routine can (e used as a modifia(lescalar value. /or e'ample* you can do t%is: mysu(12 V <K -%is is particularly useful in situations %ere you ant to use a met%od on an o(4ect toaccept a setting* instead of setting t%e value on t%e o(4ect directly. /or e'ample: su(mysu( : lvalue ^ NvalK ` ,./.1./ !rotot)pes #erl0s prototypes are not t%e prototypes in ot%er languages. Ot%er languages use prototypes to define* name and type t%e arguments to a su(routine. #erl prototypes are a(out altering t%e conte't in %ic% t%e su(routine0s arguments are evaluated* instead of t%e normal list conte't. #erl prototypes s%ould not (e used merely as a c%ec+ t%at t%e rig%t arguments %ave (een passed in. /or t%at use a module suc% as !ara-s@@Ka"idate. -%e prototype of a function can (e ,ueried (y calling prototype12. #refi' (uilt)in functions it% 3$OG@::3. prototype13$OG@::a(s32. -%e prototype function Geturns a string containing t%e prototype of t%e function or reference specified (y @X#G* or undef if t%e function %as no prototype. A su(routine0s prototype is defined in its declaration* and enforces constraints on t%e interpretation of arguments passed to it. /or e'ample: NfuncYprototype V prototype 1 3myprint3 2K print 3myprint prototype is NfuncYprototypeZn3K
314 Sree Sakthi Engineering College

su(myprint1NN2^ print 3-%is is testZn3K ` It ill produce follo ing results: "yprint prototype is NN Traps@ #rototypes do not or+ on met%ods. #rototypes do not or+ on function references. $alling a function it% a leading H 1Hfoo2 disa(les prototypes. ?ut you s%ouldn0t (e calling functions li+e t%at. ,./.# !ac&a(es A pac+age is a collection of code %ic% lives in its o n namespace. A namespace is a named collection of uni,ue varia(le names 1also called a sym(ol ta(le2. Namespaces prevent varia(le name collisions (et een pac+ages. #ac+ages ena(le t%e construction of modules %ic%* %en used* on0t clo((er varia(les and functions outside of t%e moduleMs o n namespace. The !ac&a(e State-ent pac+age statement s itc%es t%e current naming conte't to a specified namespace 1sym(ol ta(le2. If t%e named pac+age does not e'ists* a ne namespace is first created. Ni V 6K print 3NiZn3K S #rints 363 pac+age fooK Ni V 7K print 3NiZn3K S #rints 373 pac+age mainK print 3NiZn3K S #rints 363 -%e pac+age stays in effect until eit%er anot%er pac+age statement is invo+ed* or until t%e end of t%e end of t%e current (loc+ or file. 8ou can e'plicitly refer to varia(les it%in a pac+age using t%e :: pac+age ,ualifier
315 Sree Sakthi Engineering College

,./.#.1 !ac&a(e S)-bo" Tab"es -%e sym(ol ta(le is t%e list of active sym(ols 1functions varia(les o(4ects2 it%in a pac+age. @ac% pac+age %as its o n sym(ol ta(le and it% some e'ceptions all t%e identifiers starting it% letters or underscores are stored it%in t%e corresponding sym(ol ta(le for eac% pac+age. -%is means t%at all ot%er identifiers including all of t%e special punctuation)only varia(les suc% as ]E are stored it%in t%e -ain pac+age -%e sym(ol ta(le for a pac+age can (e accessed as a %as%. /or e'ample* t%e main pac+ageMs sym(ol ta(le can (e accessed as ;main:: or* more simply* as ;::. Li+e ise* sym(ol ta(les for ot%er pac+ages are ;"y"at%Li(::. -%e format is %ierarc%ical* so t%at sym(ol ta(les can (e traversed using standard #erl code. /or e'ample foreac% Nsymname 1sort +eys ;main::2 ^ local Wsym(ol V Nmain::^Nsymname`K print 3ZNNsymname is definedZn3 if defined Nsym(olK print 3ZUNsymname is definedZn3 if defined Usym(olK print 3Z;Nsymname is definedZn3 if defined ;sym(olK ` 8ou can also use t%e sym(ol ta(le to define static scalars (y assigning a value to atype glo(: W$ V 7DDED7><9K ,./.$ Specia" 5"oc&s 50.IN and 0ND 5"oc&s 8ou may define any num(er of code (loc+s named ?@GIN and @N& %ic% act as constructors and destructors respectively.
,$K&( $() P ,$K&( $() P P --- V --- V P --- V --- V

316 Sree Sakthi Engineering College

@very ?@GIN (loc+ is e'ecuted after t%e perl script is loaded and compiled (ut (efore any ot%er statement is e'ecuted.@very @N& (loc+ is e'ecuted 4ust (efore t%e perl interpreter e'its. -%e ?@GIN and @N& (loc+s are particularly useful %en creating #erl modules. ,./.' 4odu"es "odules are t%e loada(le li(raries of t%e #erl orld. A #erl module is a reusa(le pac+age defined in a li(rary file %ose name is t%e same as t%e name of t%e pac+age 1 it% a .pm on t%e end2. A #erl module is a self)contained piece of Q#erlR code t%at can (e used (y a #erl program. A #erl module file called 3/oo.pm3 mig%t contain statements li+e t%is. SbCusrC(inCperl pac+age /ooK su( (ar ^ print 3Jello NYQ:RZn3 ` su( (lat ^ print 35orld NYQ:RZn3 ` 6K Few noteab"e points about -odu"es -%e functions re,uire and use ill load a module. ?ot% use t%e list of searc% pat%s in UIN$ to find t%e module 1you may modify itb2 ?ot% call t%e eval function to process t%e code -%e 6K at t%e (ottom causes eval to evaluate to -GU@ 1and t%us not fail2 -%ere are t o ays for a module to ma+e its interface availa(le to your program: (y e'porting sym(ols or (y allo ing met%od calls. 5e0ll s%o you an e'ample of t%e first style
317 Sree Sakthi Engineering College

,./.'.1 Creatin( 4odu"es

%ereK t%e second style is for o(4ect)oriented modules and is descri(ed in t%e ne't c%apter. 1O(4ect)oriented modules s%ould e'port not%ing* since t%e %ole idea of met%ods is t%at #erl finds t%em for you automatically* (ased on t%e type of t%e o(4ect.2 -o construct a module called ?estiary* create a file called 7estiary.pm t%at loo+s li+e t%is: pac+age re,uire our UISA ?estiaryK @'porterK V , 1@'porter2K V , 1camel2K S Sym(ols to (e e'ported (y default

our U@X#OG-

our U@X#OG-YO! V , 1N eig%t2K S Sym(ols to (e e'ported on re,uest our N]@GSION V 6.::K S ]ersion num(er

SSS Include your varia(les and functions %ere su( camel ^ print 3One)%ump dromedary3 ` N eig%t V 6:7>K6K A program can no say use ?estiary to (e a(le to access t%e camel function 1(ut not t%e N eig%t varia(le2* and use ?estiary , 1camel N eig%t2 to access (ot% t%e function and t%e varia(le. ,./.'.# The 0=porter 4odu"e -%e 0=porter module supplies t%e i-port function re,uired (y t%e use statement to import functions. @'port allo s to e'port t%e functions and varia(les of modules to userMs namespace using t%e standard import met%od. -%is ay* e donMt need to create t%e o(4ects for t%e modules to access itMs mem(ers. U@X#OG- and U@X#OG-YO! are t%e t o main varia(les used during e'port operation.

318 Sree Sakthi Engineering College

U@X#OG- contains list of sym(ols 1su(routines and varia(les2 of t%e module to (e e'ported into t%e caller namespace. U@X#OG-YO! does e'port of sym(ols on demand (asis.

0=a-p"e@ Let us use t%e follo ing sample program to understand #erl e'porter. pac+age Arit%meticK use @'porterK S (ase class of t%is1Arit%metic2 module UISA V , 1@'porter2K S @'porting t%e add and su(tract routine U@X#OG- V , 1add su(tract2K S @'porting t%e multiply and divide routine on demand (asis. U@X#OG-YO! V , 1multiply divide2K su( add ^ my 1Nno6*Nno72 V UYK my NresultK Nresult V Nno6INno7K return NresultK ` ,./.'.$ Co-parin( use and re;uire 5%en you import a module* you can use one of t o +ey ords: use or re;uire.
319 Sree Sakthi Engineering College

Use @ 6. -%e met%od is used only for t%e modules1only to include .pm type file2 7. -%e included o(4ects are varified at t%e time of compilation. =. No Need to give file e'tension. S)nta=@ use "oduleK and use "odule LIS-K 0=a-p"e@ use "y"at%Li( , Cadd s,uareCK Re;uire@ 6. -%e met%od is used for (ot% li(raries and modules. 7. -%e included o(4ects are varified at t%e run time. =. Need to give file @'tension. S)nta=@ re,uire "oduleK 0=a-p"e@ re,uire 0/cntl.pl0K re,uire <.::=K ,./.'.' no If "O&UL@ supports it* t%en no calls t%e uni-port function defined in "O&UL@ to unimport all sym(ols from t%e current pac+age* or only t%e sym(ols referred to (y LIS-. It can (e said t%at no is opposite of i-port. Return Value Not%ing Syntax no "odule ]@GSION LISno "odule ]@GSION
320 Sree Sakthi Engineering College

no "O&UL@ LISno "O&UL@ ,./.'., do

5%en supplied a (loc+* do e'ecutes as if ?LO$! ere a function* returning t%e value of t%e last statement evaluated in t%e (loc+. 5%en supplied it% @X#G* do e'ecutes t%e file specified (y @X#G as if it ere anot%er #erl script. If supplied a su(routine* SU?* do e'ecutes t%e su(routine using LIS- as t%e arguments* raising an e'ception if SU? %asn.t (een defined

Syntax do ?LO$! do @X#G do SU?1LIS-2 0=a-p"e /ollo ing are t%e usage... eval ccat stat.plcK is e,uivalent to do 0stat.pl0K ,./., Scope Scope refers to t%e visi(ility of varia(les. In ot%er ords* %ic% parts of your program can see or use it. Normally* every varia(le %as a glo(al scope. Once defined* every part of your program can access a varia(le. It is very useful to (e a(le to limit a varia(le0s scope to a single function. In ot%er ords* t%e varia(le il %ave a limited scope. -%is ay* c%anges inside t%e function can0t affect t%e main program in une'pected ays* funcE.pl firstSu(13AAAAA3* 3?????32K
321 Sree Sakthi Engineering College

su( firstSu(^ local 1Nfirst]ar2 V NYQ:RK my1Nsecond]ar2 V NYQ6RK

print13firstSu(: first]ar V Nfirst]arZn32K print13firstSu(: second]ar V Nsecond]arZnZn32K secondSu(12K print13firstSu(: first]ar V Nfirst]arZn32K print13firstSu(: second]ar V Nsecond]arZnZn32K ` su( secondSu(^ print13secondSu(: first]ar V Nfirst]arZn32K print13secondSu(: second]ar V Nsecond]arZnZn32K Nfirst]ar V 3cccc$3K Nsecond]ar V 3&&&&&3K print13secondSu(: first]ar V Nfirst]arZn32K print13secondSu(: second]ar V Nsecond]arZnZn32K ` -%is program prints: firstSu(: first]ar V AAAAA firstSu(: second]ar V ????? secondSu(: first]ar V AAAAA
322 Sree Sakthi Engineering College

Use of uninitiali.ed value at test.pl line 6D. secondSu(: second]ar V secondSu(: first]ar V cccc$ secondSu(: second]ar V &&&&& firstSu(: first]ar V cccc$ firstSu(: second]ar V ????? -%e output from t%is e'ample s%o s t%at secondSu(12 could not access t%e Nsecond]ar varia(le t%at as created it% my12 inside firstSu(12. #erl even prints out an error message t%at arns a(out t%e uninitiali.ed value. -%e Nfirst]ar varia(le* %o ever* can (e accessed and valued (y secondSu(12. ,./.,.1 0ffects of -) &eclares t%e varia(les in LIS- to (e le'ically scoped it%in t%e enclosing (loc+. If more t%an one varia(le is specified* all varia(les must (e enclosed in parent%eses Return Ka"ue Not%ing Syntax my LIS0=a-p"e SbCusrC(inCperl ) my Nstring V 35e are t%e orld3K print 3NstringZn3K myfunction12K print 3NstringZn3K su( myfunction
323 Sree Sakthi Engineering College

^ my Nstring V 35e are t%e function3K print 3NstringZn3K mysu(12K ` su( mysu( ^ print 3NstringZn3K ` It wi"" produce fo""owin( resu"ts@ 5e are t%e orld 5e are t%e function 5e are t%e orld 5e are t%e orld ,./.,.# 0ffects of "oca" Sets t%e varia(les in LIS- to (e local to t%e current e'ecution (loc+. If more t%an one value is specified* you must use parent%eses to define t%e list. Note t%at local creates a local copy of a varia(le* %ic% t%en goes out of scope %en t%e enclosing (loc+ terminates. -%e locali.ed value is t%en used %enever it is accessed* including any su(routines and formats used during t%at (loc+. Return Value Not%ing Syntax local LISExample SbCusrC(inCperl )

324 Sree Sakthi Engineering College

local NfooK local 1U id* ;get2K local Nfoo V 3flurp3K local Uoof V U(arK ,./.,.$ 0ffects of our

S ma+e Nfoo dynamically local S ma+e list of varia(les local S ma+e Nfoo dynamic* and init it S ma+e Uoof dynamic* and init it

&efines t%e varia(les specified in LIS- as (eing glo(al it%in t%e enclosing (loc+* file* or eval statement. It is effectively t%e opposite of my.it declares a varia(le to (e glo(al it%in t%e entire scope* rat%er t%an creating a ne private varia(le of t%e same name. All ot%er options are identical to myK An our declaration declares a glo(al varia(le t%at ill (e visi(le across its entire le'ical scope* even across pac+age (oundaries. -%e pac+age in %ic% t%e varia(le is entered is determined at t%e point of t%e declaration* not at t%e point of use. If more t%an one value is listed* t%e list must (e placed in parent%eses. Return Ka"ue

not%ing

Syntax our @X#G our @X#G -8#@ our @X#G : A--GS our -8#@ @X#G : A--GS 0=a-p"e -ry out follo ing e'ample: SbCusrC(inCperl ) our Nstring V 35e are t%e orld3K print 3NstringZn3K myfunction12K
325 Sree Sakthi Engineering College

print 3NstringZn3K su( myfunction ^ our Nstring V 35e are t%e function3K print 3NstringZn3K ` It ill produce follo ing results: 5e are t%e orld 5e are t%e function 5e are t%e function ,./.,.' Scope Within 2oops -%ere is a slig%tly special case %en declaring a varia(le in a loop statement. In t%e fragment* foreac% my N+ey 1sort +eys ;%as%2 ^ ... ` t%e N+ey varia(le is le'ically defined for t%e duration of t%e entire statement* itMs accessi(le or ot%er statement2* (ut it immediately disappears %en t%e loop terminates. Jo ever* (e careful %ere you define t%e varia(le. In t%e fragment* do ^ my Nvar V 6K ` %ile 1Nvar2K t%e Nvar used in t%e test %as no valueaonly t%e Nvar in t%e (loc+ %as a value. ,././ *uto"oadin( %ic% means t%at %ile it%in t%e (loc+ t%at ma+es up t%e loop 1including any continue (loc+ in a

326 Sree Sakthi Engineering College

Autoloading is a ay to intercept calls to undefined met%ods. An autoload routine may c%oose to create a ne function on t%e fly* eit%er loaded from dis+ or per%aps 4ust eval12ed rig%t t%ere.-%e AU-OLOA& su(routine is called it% all t%e same arguments as t%e un+no n routine* and t%e fully ,ualified su(routine name is placed into t%e NAU-OLOA& varia(le. Normally* you can0t call a su(routine t%at isn0t defined. Jo ever* if t%ere is a su(routine named AU-OLOA& in t%e undefined su(routine0s pac+age. -%e AU-OLOA& module can also (e used directly it%in a #erl script to add (lan+et functionality to a script it%out re,uiring you to create many su(routines. 0=a-p"e@ ?@GIN ^ Nconstants^3#I3` V =.6>6<D7B<>K ` use su(s +eys ;constantsK print 3-%e value of #I is 3*#IK su( AU-OLOA& ^ my Nconstant V NAU-OLOA&K Nconstant VO sC.W::CCK return Nconstants^3Nconstant3`K ` ,.1 Wor&in( with Fi"es ,.1.1 Fi"ehand"es -%e (asics of %andling files are simple: you associate a file%andle it% an e'ternal entity 1usually a file2 and t%en use a variety of operators and functions it%in #erl to read and update t%e data stored it%in t%e data stream associated it% t%e file%andle. A file%andle is a named internal #erl structure t%at associates a p%ysical file it% a name. All file%andles are capa(le of readC rite access* so you can read from and update any file or
327 Sree Sakthi Engineering College

device associated it% a file%andle. Jo ever* %en you associate a file%andle* you can specify t%e mode in %ic% t%e file%andle is opened. -%ree (asic file %andles are ) STDIN* STDOUT* and STD0RR. -%e general sc%eme loo+s li+e t%is:

,.1.1.1 Openin( and C"osin( Fi"es -%ere are follo ing t o functions it% multiple forms %ic% can (e used to open any ne or e'isting file in #erl. open /IL@JAN&L@* @X#G open /IL@JAN&L@ sysopen /IL@JAN&L@* /IL@NA"@* "O&@* #@G"S sysopen /IL@JAN&L@* /IL@NA"@* "O&@ Jere /IL@JAN&L@ is t%e file %andle returned (y open function and @X#G is t%e e'pression %aving file name and mode of opening t%e file. /ollo ing is t%e synta' to open file.t't in read)only mode. Jere less t%an Tsigne indicates t%at file %as to (e opend in read)only mode. open1&A-A* 3Tfile.t't32K Jere &A-A is t%e file %andle %ic% ill (e used to read t%e file. Jere is t%e e'ample %ic% ill open a file and ill print its content over t%e screen. SbCusrC(inCperl open1&A-A* 3Tfile.t't32K %ile1T&A-AP2 ^
328 Sree Sakthi Engineering College

print 3NY3K ` Open Function /ollo ing is t%e synta' to open file.t't in riting mode. Jere less t%an Psigne indicates t%at file %as to (e opend in riting mode open1&A-A* XPfile.t'tF2K -%is e'ample actually truncates 1empties2 t%e file (efore opening it for riting* %ic% may not (e t%e desired effect. If you ant to open a file for reading and riting* you can put a plus sign (efore t%e P or T c%aracters. /or e'ample* to open a file for updating it%out truncating it: open1&A-A* XIfile.t'tF2K -o truncate t%e file first: open &A-A* 3IPfile.t't3 or die X$ouldn0t open file file.t't* NbFK 8ou can open a file in append mode. In t%is mode riting point ill (e set to t%e end of t%e file open1&A-A*3PPfile.t't32 __ die 3$ouldn0t open file file.t't* Nb3K A dou(le PP opens t%e file for appending* placing t%e file pointer at t%e end* so t%at you can immediately start appending information. Jo ever* you can.t read from it unless you also place a plus sign in front of it: open1&A-A*3IPPfile.t't32 __ die 3$ouldn0t open file file.t't* Nb3K /ollo ing is t%e ta(le %ic% gives possi(le values of different modes 0ntities T or r P or PP or a IT or rI IP or I Definition Gead Only Access $reates* 5rites* and -runcates 5rites* Appends* and $reates Geads and 5rites Geads* 5rites* $reates* and -runcates

IPP or aI Geads* 5rites* Appends* and $reates S)sopen Function


329 Sree Sakthi Engineering College

-%e sysopen function is similar to t%e main open function* e'cept t%at it uses t%e system open12 function* using t%e parameters supplied to it as t%e parameters for t%e system function: /or e'ample* to open a file for updating* emulating t%e ITfilename format from open: sysopen1&A-A* 3file.t't3* OYG&5G2K or to truncate t%e file (efore updating: sysopen1&A-A* 3file.t't3* OYG&5G_OY-GUN$ 2K 8ou can use OY$G@A- to create a ne file and OY5GONL8) to open file in rite only mode and OYG&ONL8 ) to open file in read only mode. -%e #@G"S argument specifies t%e file permissions for t%e file specified if it %as to (e created. ?y default it ta+es :'BBB. /ollo ing is t%e ta(le %ic% gives possi(le values of "O&@ Ka"ue OYG&5G Definition Gead and 5rite

OYG&ONL8 Gead Only OY5GONL8 5rite Only OY$G@AOY-GUN$ OY@X$L OYNON?LO$! C"ose Function $reate t%e file -runcate t%e file Stops if file already e'ists Non)?loc+ing usa(ility OYA##@N& Append t%e file

-o close a file%andle* and t%erefore disassociate t%e file%andle from t%e corresponding file* you use t%e close function. -%is flus%es t%e file%andle0s (uffers and closes t%e system0s file descriptor. close /IL@JAN&L@ close If no /IL@JAN&L@ is specified* t%en it closes t%e currently selected file%andle. It returns true only if it could successfully flus% t%e (uffers and close t%e file. close1&A-A2 __ die 3$ouldn0t close file properly3K ,.1.1.# Readin( and Writin( Fi"ehand"es
330 Sree Sakthi Engineering College

Once you %ave an open file%andle* you need to (e a(le to read and rite information. -%ere are a num(er of different ays of reading and riting data into t%e file. The XFI20>*ND2U Operator -%e main met%od of reading t%e information from an open file%andle is t%e T/IL@JAN&L@P operator. In a scalar conte't it returns a single line from t%e file%andle. /or e'ample: SbCusrC(inCperl print 35%at is your nameAZn3K Nname V TS-&INPK print 3Jello NnameZn3K 5%en you use t%e T/IL@JAN&L@P operator in a list conte't* it returns a list of lines from t%e specified file%andle. /or e'ample* to import all t%e lines from a file into an array: SbCusrC(inCperl open1&A-A*3Timport.t't32 or die 3$an0t open data3K Ulines V T&A-APK close1&A-A2K (etc Function -%e getc function returns a single c%aracter from t%e specified /IL@JAN&L@* or S-&IN if none is specified: getc /IL@JAN&L@ getc If t%ere as an error* or t%e file%andle is at end of file* t%en undef is returned instead. read Function -%e read function reads a (loc+ of information from t%e (uffered file%andle: -%is function is used to read (inary data from t%e file. read /IL@JAN&L@* S$ALAG* L@NG-J* O//S@read /IL@JAN&L@* S$ALAG* L@NG-J -%e lengt% of t%e data read is defined (y L@NG-J* and t%e data is placed at t%e start of S$ALAG if no O//S@- is specified. Ot%er ise data is placed after O//S@- (ytes in S$ALAG.
331 Sree Sakthi Engineering College

-%e function returns t%e num(er of (ytes read on success* .ero at end of file* or undef if t%ere as an error. print Function /or all t%e different met%ods used for reading information from file%andles* t%e main function for riting information (ac+ is t%e print function. print /IL@JAN&L@ LISprint LISprint -%e print function prints t%e evaluated value of LIS- to /IL@JAN&L@* or to t%e current output file%andle 1S-&OU- (y default2. /or e'ample: print 3Jello 5orldbZn3K Cop)in( Fi"es Jere is t%e e'ample %ic% opens an e'isting file file6.t't and read it line (y line and generate anot%er copy file7.t't SbCusrC(inCperl S Open file to read open1&A-A6* 3Tfile6.t't32K S Open ne file to rite open1&A-A7* 3Pfile7.t't32K S $opy data from one file to anot%er. %ile1T&A-A6P2 ^ print &A-A7 NYK ` close1 &A-A6 2K close1 &A-A7 2K Rena-in( a fi"e
332 Sree Sakthi Engineering College

Jere is an e'ample %ic% s%o s %o availa(le in CusrCtest directory. SbCusrC(inCperl

e can rename a file file6.t't to file7.t't. Assuming file is

rename 13CusrCtestCfile6.t't3* 3CusrCtestCfile7.t't3 2K -%is function rename ta+es t o arguments and it 4ust rename e'isting file De"etin( an e=itin( fi"e Jere is an e'ample %ic% s%o s %o to delete a file file6.t't using unlin+ function. SbCusrC(inCperl unlin+ 13CusrCtestCfile6.t't32K ,.1.1.$ 2ocatin( 9our !osition Within a Fi"e 8ou can use to tell function to +no t%e current position of a file and see+ function to point a particular position inside t%e file. te"" Function -%e first re,uirement is to find your position it%in a file* %ic% you do using t%e tell function: tell /IL@JAN&L@ tell -%is returns t%e position of t%e file pointer* in (ytes* it%in /IL@JAN&L@ if specified* or t%e current default selected file%andle if none is specified. see& Function -%e see+ function positions t%e file pointer to t%e specified num(er of (ytes it%in a file: see+ /IL@JAN&L@* #OSI-ION* 5J@N$@ -%e function uses t%e fsee+ system function* and you %ave t%e same a(ility to position relative to t%ree different points: t%e start* t%e end* and t%e current position. 8ou do t%is (y specifying a value for 5J@N$@. \ero sets t%e positioning relative to t%e start of t%e file. /or e'ample* t%e line sets t%e file pointer to t%e 7<Bt% (yte in t%e file. see+ &A-A* 7<B* :K ,.1.1.' 4isce""aneous Contro" Functions bin-ode@
333 Sree Sakthi Engineering College

Sets t%e format for /IL@JAN&L@ to (e read from and ritten to as (inary on t%e operating systems t%at differentiate (et een t%e t o. /iles t%at are not in (inary %ave $G L/ se,uences converted to L/ on input* and L/ to $G L/ on output. -%is is vital for operating systems t%at use t o c%aracters to separate lines it%in te't files 1"S)&OS2* (ut %as no effect on operating systems t%at use single c%aracters 1Uni'* "ac OS* [NX2. Return Ka"ue undef on failure or invalid /IL@JAN&L@. 6 on success. S)nta= (inmode /IL@JAN&L@ eof@ Geturns 6 if t%e ne't read on /IL@JAN&L@ ill return end of file* or if /IL@JAN&L@ is not open. An eof it%out an argument uses t%e last file read. Using eof12 it% empty parent%eses is very different. It refers to t%e pseudo file formed from t%e files listed on t%e command line and accessed via t%e TP operator. Return Ka"ue undef if /IL@JAN&L@ is not at end of file 6 if /IL@JAN&L@ ill report end of file on ne't read S)nta= eof /IL@JAN&L@ eof12 eof 0=a-p"e S insert das%es 4ust (efore last line of last file %ile 1TP2 ^ if 1eof122 ^ ` printK
334 Sree Sakthi Engineering College

S c%ec+ for end of last file

print 3))))))))))))))Zn3K

last if eof12K S needed if e0re reading from a terminal ` fi"eno@ Geturns t%e file descriptor num(er 1as used (y $ and #OSIX functions2 of t%e specified /IL@JAN&L@. -%is is generally useful only for using t%e select function and any lo )level tty functions. Return Ka"ue /ile descriptor 1numeric2 of /IL@JAN&L@ undef on failure S)nta= fileno /IL@JAN&L@ 0=a-p"e 8ou can use t%is to find out %et%er t o %andles refer to t%e same underlying descriptor: if 1fileno1-JIS2 VV fileno1-JA-22 ^ print 3-JIS and -JA- are dupsZn3K ` se"ece@ Sets t%e default file%andle for output to /IL@JAN&L@* setting t%e file%andle used (y functions suc% as print and rite if no file%andle is specified. If /IL@JAN&L@ is not specified* t%en it returns t%e name of t%e current default file%andle. select 1G?I-S* 5?I-S* @?I-S* -I"@OU- 2$alls t%e system function select1 2 using t%e (its specified. -%e select function sets t%e controls for %andling non)(loc+ing ICO re,uests. Geturns t%e num(er of file%andles a aiting ICO in scalar conte't* or t%e num(er of aiting file%andles and t%e time remaining in a list conte't. Return Ka"ue #revious default file%andle if /IL@JAN&L@ specified $urrent default file%andle if /IL@JAN&L@ is not specified S)nta= select /IL@JAN&L@
335 Sree Sakthi Engineering College

select select G?I-S* 5?I-S* @?I-S* -I"@OU0=a-p"e SbCusrC(inCperl ) open1/IL@*3PCtmpCt.out32K NoldJandle V select1/IL@2K print13-%is is sent to CtmpCt.out.Zn32K select1NoldJandle2K print13-%is is sent to S-&OU-.Zn32K truncate@ -runcates 1reduces2 t%e si.e of t%e file specified (y /IL@JAN&L@ to t%e specified L@NG-J 1in (ytes2. #roduces a fatal error if t%e function is not implemented on your system. Return Ka"ue undef if t%e operation failed 6 on success S)nta= truncate /IL@JAN&L@* L@NG-J 0=a-p"e /ollo ing e'ample ill truncate file 3test.t't3 to .ero lengt%. SbCusrC(inCperl ) open1 /IL@* 3TCtmpCtest.t't3 2 __ die 3@na(le to open test file3K truncate1 /IL@* : 2K close1/IL@2K ,.1.# Fi"e 4ana(e-ent ,.1.#.1 Fi"e Infor-ation 8ou can test certain features very ,uic+ly it%in #erl using a series of test operators +no n collectively as )X tests.
336 Sree Sakthi Engineering College

/or e'ample* to perform a ,uic+ test of t%e various permissions on a file* you mig%t use a script li+e t%is: SCusrC(inCperl my 1Udescription*Nsi.e2K if 1)e Nfile2 ^ pus% Udescription* 0(inary0 if 1)? Y2K pus% Udescription* 0a soc+et0 if 1)S Y2K pus% Udescription* 0a te't file0 if 1)- Y2K pus% Udescription* 0a (loc+ special file0 if 1)( Y2K pus% Udescription* 0a c%aracter special file0 if 1)c Y2K pus% Udescription* 0a directory0 if 1)d Y2K pus% Udescription* 0e'ecuta(le0 if 1)' Y2K pus% Udescription* 11Nsi.e V )s Y22 A 3Nsi.e (ytes3 : 0empty0K print 3Nfile is 3* 4oin10* 0*Udescription2*3Zn3K ` Jere is t%e list of features %ic% you can c%ec+ for a file Operator Description )A Age of file 1at script startup2 in days since modification. )? Is it a (inary fileA )$ Age of file 1at script startup2 in days since modification. )" Age of file 1at script startup2 in days since modification. )O Is t%e file o ned (y t%e real user I&A )G Is t%e file reada(le (y t%e real user I& or real groupA )S Is t%e file a soc+etA )Is it a te't fileA )5 Is t%e file rita(le (y t%e real user I& or real groupA )X Is t%e file e'ecuta(le (y t%e real user I& or real groupA )( Is it a (loc+ special fileA )c Is it a c%aracter special fileA )d Is t%e file a directoryA )e &oes t%e file e'istA )f Is it a plain fileA )g &oes t%e file %ave t%e setgid (it setA )+ &oes t%e file %ave t%e stic+y (it setA )l Is t%e file a sym(olic lin+A )o Is t%e file o ned (y t%e effective user I&A
337 Sree Sakthi Engineering College

)p )r )s )t )u ) )' ).

Is t%e file a named pipeA Is t%e file reada(le (y t%e effective user or group I&A Geturns t%e si.e of t%e file* .ero si.e V empty file. Is t%e file%andle opened (y a --8 1terminal2A &oes t%e file %ave t%e setuid (it setA Is t%e file rita(le (y t%e effective user or group I&A Is t%e file e'ecuta(le (y t%e effective user or group I&A Is t%e file si.e .eroA

,.1.#.# 5asic Fi"e 4ana(e-ent In uni' OS* files are created on a file system (y creating a lin+ to an inode* %ic% creates t%e necessary directory entry t%at lin+s to t%e file data. rena-e@ Genames t%e file it% OL&NA"@ to N@5NA"@. Uses t%e system function rename1 2* and so it ill not rename files across file systems or volumes. If you ant to copy or move a file* use t%e copy or move command supplied in t%e /ile $opy module. Return Ka"ue : on failure 6 on success S)nta= rename OL&NA"@* N@5NA"@ 0=a-p"e /irst create test file in Ctmp directory and t%en use follo ing code to c%ange file name. SbCusrC(inCperl ) rename13CtmpCtest3* 3CtmpCtest732 __ die 1 3@rror in renaming3 2K "in&@ $reates a ne file name* N@5/IL@* lin+ed to t%e file OL&/IL@. -%e function creates a %ard lin+K if you ant a sym(olic lin+* use t%e symlin+ function. Return Ka"ue
338 Sree Sakthi Engineering College

: on failure and 6 on success S)nta= lin+ OL&/IL@*N@5/IL@ 0=a-p"e -%is ill create ne file using e'isting file. SbCusrC(inCperl Ne'istingYfile V 3CuerC%omeCtest63K Nne Yfile V 3CusrC%omeCtest73K Nretval V lin+ Ne'istingYfile* Nne Yfile K if1 Nretval VV 6 2^ print3Lin+ created successfullyZn3K `else^ print3@rror in creating lin+ NbZn3K ` s)-"in&@ $reates a sym(olic lin+ (et een OL&/IL@ and N@5/IL@. On systems t%at don0t support sym(olic lin+s* causes a fatal error. Return Ka"ue : on failure 6 on success S)nta= symlin+ 1 OL&/IL@* N@5/IL@ 2 0=a-p"e /irst create one file test.t't in Ctmp directory and t%en try out follo ing e'ample it ill create a sym(olic lin+ in t%e same directory: SbCusrC(inCperl ) symlin+13CtmpCte't.t't3* 3CtmpCsymlin+YtoYte't.t't32K un"in&@
339 Sree Sakthi Engineering College

&eletes t%e files specified (y LIS-* or t%e file specified (y NY ot%er ise. ?e careful %ile using t%is function (ecause t%ere is no recovering once a file gets deleted. Return Ka"ue Num(er of files deleted. S)nta= unlin+ LISunlin+ 0=a-p"e $reate t o files t6.t't and t7.t't in Ctmp directory and t%en use t%e follo ing program to delete t%ese t o files. SbCusrC(inCperl ) unlin+1 3CtmpCt6.t't3* 3CtmpCt7.t't3 2K It ill produce follo ing results: ?ot% t%e files t6.t't and t7.t't ill (e deleted from Ctmp. read"in&@ Geturns t%e pat%name of t%e file pointed to (y t%e lin+ @X#G* or NY if @X#G is not specified. Return Ka"ue undef on error ot%er ise pat%name of t%e file S)nta= readlin+ @X#G readlin+ 0=a-p"e SbCusrC(inCperl ) S assume CtmpCtest is a sym(olic lin+ on CtmpCusrCtest.pl readlin+ 3CtmpCtest3K It ill produce follo ing results:
340 Sree Sakthi Engineering College

CtmpCusrCtest.pl ch-od@ $%anges t%e mode of t%e files specified in LIS- to t%e "O&@ specified. -%e value of "O&@ s%ould (e in octal. 8ou must c%ec+ t%e return value against t%e num(er of files t%at you attempted to c%ange to determine %et%er t%e operation failed. -%is funcation call is e,uivalent to Uni' $ommand c%mod "O&@ /IL@LIS-. Return Ka"ue Integer* num(er of files successfully c%anged S)nta= c%mod "O&@* LIS0=a-p"e Ncnt V c%mod :E<<* 0foo0* 0(ar0K c%mod :E<<* Ue'ecuta(lesK Nmode V 0:B>>0K c%mod Nmode* 0foo0K S )) ))))r)Nmode V 0:B>>0K c%modoct1Nmode2* 0foo0K S t%is is (etter Nmode V :B>>K c%mod Nmode* 0foo0K chown@ $%anges t%e o ner 1and group2 of a list of files. -%e first t o elements of t%e list must (e t%e numeric uid and gid* in t%at order. -%is funcation call or+s in similar ay as uni' command c%o n. -%us you s%ould %ave sufficient privilege to c%ange t%e permission of t%e file. Return Ka"ue Geturns t%e num(er of files successfully c%anged. S)nta= c%o n US@GI&* GGOU#I&* LIS0=a-p"e Jere is an e'ample %ic% ill c%ange o ners%ip for t%e given num(er of files. SbCusrC(inCperl
341 Sree Sakthi Engineering College

S bbb sets mode to

S t%is is (est

Ncnt V c%o n Nuid* Ngid* 0foo0* 0(ar0K c%o n Nuid* Ngid* UfilenamesK uti-e@ Sets t%e access and modification times specified (y A-I"@ and "-I"@ for t%e list of files in LIS-. -%e values of A-I"@ and "-I"@ must (e numerical. -%e inode modification time is set to t%e current time. -%e time must (e in t%e numeric format 1for e'ample* seconds since Lanuary 6* 6DE:2. Return Ka"ue Num(er of files updated S)nta= utime A-I"@* "-I"@* LIS0=a-p"e $reate a file t.t't in Ctmp directory and use t%e follo ing program to set its modification and access time to t%e current time. SbCusrC(inCperl ) utime1time12* time12* 3CtmpCt.t't32K u-as&@ Sets t%e umas+ 1default mas+ applied %en creating files and directories2 for t%e current process. ]alue of @X#G must (e an octal num(er. If @X#G is omitted* simply returns t%e previous value. Return Ka"ue #revious umas+ value S)nta= umas+ @X#G umas+ 0=a-p"e SbCusrC(inCperl ) print13-%e current umas+ is: 3* umas+12* 3Zn32K It ill produce follo ing results* you can get different result on your computer (ased on your setting.
342 Sree Sakthi Engineering College

-%e current umas+ is: 69 ,.1.#.$ *ccessin( Director) 0ntries /ollo ing are t%e standard functions used to play it% directories. opendir &IGJAN&L@* @X#G S -o open a directory readdir &IGJAN&L@ S -o read a directory re inddir &IGJAN&L@ S #ositioning pointer to t%e (egining telldir &IGJAN&L@ S Geturns current position of t%e dir see+dir &IGJAN&L@* #OS S #ointing pointer to #OS inside dir closedir &IGJAN&L@ S $losing a directory. Jere is an e'ample %ic% opens a directory and list out all t%e files availa(le inside t%is directory. SbCusrC(inCperl opendir 1&IG* 0.02 or die 3$ouldn0t open directory* Nb3K %ile 1Nfile V readdir &IG2 ^ print 3NfileZn3K ` closedir &IGK Anot%er e'ample to print t%e list of $ source code files* you mig%t use SbCusrC(inCperl opendir1&IG* 0.02 or die 3$ouldn0t open directory* Nb3K foreac% 1sort grep1Cf.WZ.cNC*readdir1&IG222 ^ print 3NYZn3K ` closedir &IGK 8ou can ma+e a ne directory using t%e m+dir function: -o remove a directory* use t%e rmdir function: -o c%ange t%e directory you can use c%dir function. ,.1.#.' 4ana(in( Directories
343 Sree Sakthi Engineering College

-%e system c%dir12 function is supported it%in #erl in order to c%ange t%e current directory for t%e current process. chdir@ $%anges t%e current or+ing directory to @X#G* or to t%e user0s %ome directory if none is specified. -%is function call is e,uivalent to Uni' command cd @X#G. Return Ka"ue : on failure 6 on success S)nta= chdir 0A!R chdir 0=a-p"e Assuming you are or+ing in CuserC%omeCtutorialspoint directory. @'ecute follo ing program: SbCusrC(inCperl c%dir 3CusrC%ome3K S No you are in CusrC%ome dir. c%dirK S No you are in %ome directory CuserC%omeCtutorialspoint -&dir@ 8ou can ma+e a ne directory using t%e m+dirfunction."a+es a directory it% t%e name and pat% @X#G using t%e mode specified (y "O&@* %ic% s%ould (e supplied as an octal value for clarity. Return Ka"ue : on failure 6 on success S)nta= m+dir @X#G*"O&@ 0=a-p"e
344 Sree Sakthi Engineering College

SbCusrC(inCperl ) Ndirname V3CtmpCtestdir3K m+dir Ndirname* :E<<K It ill produce follo ing results in Ctmp directory: dr 'r)'r)' 7 root root r-dir@ &eletes t%e directory specified (y @X#G* or NY if omitted. Only deletes t%e directory if t%e directory is empty. Return Ka"ue : on failure 6 on success S)nta= rmdir @X#G rmdir 0=a-p"e $reate one directory testdir inside Ctmp and -ry out follo ing e'ample: SbCusrC(inCperl ) rmdir 13CtmpCtestdir32 __ die 13error in deleting directory: NA32K It ill produce follo ing results: If directory is empty t%en it ill (e deleted ot%er ise error message ill (e generated. ,.1.#., Fi"e Contro" with fcnt" #erforms t%e function specified (y /UN$-ION* using S$ALAG on /IL@JAN&L@. S$ALAG eit%er contains a value to (e used (y t%e function or is t%e location of any returned information. Return Ka"ue : (ut true if t%e return value from t%e fcntl12is : ]alue returned (y system. undef on failure
345 Sree Sakthi Engineering College

>:DB "ar 6D 66:<< testdir

S)nta=@ fcntl /IL@JAN&L@* /UN$-ION* S$ALAG 0=a-p"e use /cntlK fcntl1Nfile%andle* /YG@-/L* Npac+edYreturnY(uffer2 or die 3can0t fcntl /YG@-/L: Nb3K ,.1.#./ I:O Contro" with ioct" -%e ioctl function is similar in principle to t%e fcntl function. It too is a #erl version of t%e operating system e,uivalent ioctl12 function. -%e ioctl function is typically used to set options on devices and data streams* usually relating directly to t%e operation of t%e terminal. Return Ka"ue undef on failure ot%er ise : (ut true if t%e return value from t%e ioctl1 2is : S)nta= ioctl /IL@JAN&L@* /UN$-ION* S$ALAG ,.1.#.1 Fi"e 2oc&in( /ile loc+ing is a ay of ensuring t%e integrity of files. It allo s many people 1actually* processes2 to s%are a file in a safe ay* it%out stepping on eac% ot%er0s toes. Supports file loc+ing on t%e specified /IL@JAN&L@ using t%e system floc+1 2* fcntl1 2 loc+ing* or loc+f1 2. -%e e'act implementation used is dependent on %at your system supports. O#@GA-ION is one of t%e static values defined %ere... Operation LO$!YSJ LO$!Y@X LO$!YUN LONGYN? Return Ka"ue : on failure to setCunset loc+ 6 on success to setCunset loc+
346 Sree Sakthi Engineering College

Resu"t Set s%ared loc+. Set e'clusive loc+. Unloc+ specified file. Set loc+ it%out (loc+ing.

S)nta= floc+ /IL@JAN&L@* O#@GA-ION 0=a-p"e Jere0s a mail(o' appender for ?S& systems: use /cntl 0:floc+0K S import LO$!YW constants su( loc+ ^ floc+1"?OX*LO$!Y@X2K S and* in case someone appended S %ile e ere aiting... see+1"?OX* :* 72K ` su( unloc+ ^ floc+1"?OX*LO$!YUN2K ` open1"?OX* 3PPCusrCspoolCmailCN@N]^0US@G0`32 or die 3$an0t open mail(o': Nb3K loc+12K print "?OX Nmsg*3ZnZn3K unloc+12K

,.3. Data 4anipu"ation #erl as originally designed as a system for processing logs and reporting on t%e information.-%e data)manipulation features (uilt into #erl* from t%e (asics of numerical calculations t%roug% to (asic string %andling. ,.3.1. Wor&in( with Nu-bers Num(ers are scalar data. -%ey e'ist in #@GL as real num(ers* float* integers* e'ponents* octal* and %e'adecimal num(ers. ,.3.1.1 abs8the *bso"ute Ka"ue Geturns t%e a(solute value of its argument. If pure interger value is passed t%en it ill return it as it is (ut if a string is passed t%en it ill return .ero. If ]ALU@ is omitted t%en it uses NY. Return Ka"ue
347 Sree Sakthi Engineering College

Geturns t%e a(solute value of its argument. S)nta= a(s ]ALU@ a(s 0=a-p"e print a(s1)6.7D<>EB2K -%is s%ould print a value of 6.7D<>EB. Supplying a positive value to a(s ill return t%e same positive value or* more correctly* it ill return t%e nondesignated value: all positive values imply a I sign in front of t%em. ,.3.1.# int8Con%ertin( F"oatin( !oints to Inte(ers Geturns t%e integer element of @X#G* or NY if omitted. -%e int function does not do rounding. If you need to round a value up to an integer* you s%ould use sprintf. Return Ka"ue Integer part of @X#G. 0=a-p"e printint a(s1)6.7D<>EB2K -%is s%ould print a value of 6. -%e only pro(lem it% t%e int function is t%at it strictly removes t%e fractional component of a num(erK no rounding of any sort is done. If you ant to return a num(er t%at %as (een rounded to a num(er of decimal places* use t%e printf or sprintf function: printf13;.7f3*a(s1)6.7D<>EB22K -%is ill round t%e num(er to t o decimal places)a value of 6.=: in t%is e'ample. Note t%at t%e : is appended in t%e output to s%o t%e t o decimal places. ,.3.1.$ e=p8Raisin( e to the !ower -o perform a normal e'ponentiation operation on a num(er* you use t%e WW operator: Ns,uare ) >WW7K -%is returns 6B* or > raised to t%e po er of 7. If you ant to raise t%e natural (ase num(er e to t%e po er* you need to use t%e e'p function: e'p @X#G
348 Sree Sakthi Engineering College

e'p If you do not supply an @X#G argument* e'p uses t%e value of t%e NYvaria(le as t%e e'ponent. /or e'ample* to find t%e s,uare of e: Ns,uare )e'p172K ,.3.1.' s;rt8the S;uare Root -o get t%e s,uare root of a num(er* use t%e (uilt)in s,rt function: Nvar)s,rt16B=9>2K -o calculate t%e nt% root of a num(er* use t%e WW operator it% a fractional num(er. /or e'ample* t%e follo ing line Nvar) 6B=9>WW16C72K is identical to Nvar)s,rt16B=9>2K -o find t%e cu(e root of 6B*EEE*76B* you mig%t use Nvar) 6BEEE76BWW16C=2K %ic% s%ould return a value of 7<B. ,.3.1.,"o(8the 2o(arith-o find t%e logarit%m 1(ase e2 of a num(er* you need to use t%e log function: Nlog ) log 6.>=K ,.3.1./Tri(ono-etric Functions -%ere are t%ree (uilt)in trigonometric functions for calculating t%e arctangent s,uared 1atan72* cosine 1cos2* and sine 1sin2 of a value: atan7 X*8 cos @X#G sin @X#G If you need access to t%e arcsine* arccosine* and tangent* t%en use t%e #OSIX module* %ic% supplies t%e corresponding acos* asin* and tan functions. Unless you are doing trigonometric calculations* t%ere is little use for t%ese functions in everyday life. Jo ever* you can use t%e sin function to calculate your (ior%yt%ms using t%e simple script s%o n ne't* assuming you +no t%e num(er
349 Sree Sakthi Engineering College

of days you %ave (een alive: my 1Np%ysYstep* NemotYstep* NinteYstep2 ) 17=* 79* ==2K use "at%::$omple'K print 3@nter t%e num(er of days you (een alive:Zn3K my Nalive )TS-&INPK Np%ys)int1sin111piW1Nalive;Np%ysYstep22C1Np%ysYstepC7222W6::2K Nemot)int1sin111piW1Nalive;NemotYstep22C1NemotYstepC7222W6::2K Ninte)int1sin111piW1Nalive;NinteYstep22C1NinteYstepC7222W6::2K print 38our #%ysical is Np%ys;* @motional Nemot;* Intellectual Ninte;Zn3K ,.3.1.1 Con%ersion between 5ases #erl provides automatic conversion to decimal for numerical literals specified in (inary* octal* and %e'adecimal. Jo ever* t%e translation is not automatic on values contained it%in strings* eit%er t%ose defined using string literals or from strings imported from t%e outside orld 1files* user input* etc.2. -o convert a string)(ased literal* use t%e oct or %e' functions. -%e %e' function converts only %e'adecimal num(ers supplied it% or it%out t%e :' prefi'. /or e'ample* t%e decimal value of t%e %e'adecimal string Xff>Eace=F 1>7*979*9E=*D<>2 can (e displayed it% eit%er of t%e follo ing statements: print %e'13ff>Eace=32K print %e'13:'ff>Eace=32K -%e %e' function doesnMt or+ it% ot%er num(er formats* so for strings t%at start it% :* :(* or :'* you are (etter off using t%e oct function. ?y default* t%e oct function interprets a string it%out a prefi' as an octal string and raises an error if it doesnMt see it. So t%is printoct13E<<32K is valid* (ut t%is printoct13aef32K ill fail.
350 Sree Sakthi Engineering College

If you supply a string using one of t%e literal formats t%at provides t%e necessary prefi'* oct ill convert it* so all of t%e follo ing are valid: printoct13:E<<32K printoct13:'Ef32K printoct13:(::6::::632K ?ot% oct and %e' default to using t%e NY varia(le if you fail to supply an argument. -o print out a decimal value in %e'adecimal* (inary* or octal* use printf* or use sprintf to print a formatted (ase num(er to a string: printf 13;l( ;lo ;l'3* oct13:(:::6:::632* oct13:E<<32* oct13:'Ef322K See printf in $%apter E for more information. ,.3.1.3Con%ersion 5etween Characters and Nu-bers If you ant to insert a specific c%aracter into a string (y its numerical value* you can use t%e Z: or Z' c%aracter escapes: print 3Z::E3K print 3Z':E3K -%ese e'amples print t%e octal and %e'adecimal valuesK in t%is case t%e X(ellF c%aracter. Often* t%oug%* it is useful to (e a(le to specify a c%aracter (y its decimal num(er and to convert t%e c%aracter (ac+ to its decimal e,uivalent in t%e AS$II ta(le. -%e c%r function returns t%e c%aracter matc%ing t%e value of @X#G* or NYif @X#G is not specified. -%e value is matc%ed against t%e current AS$II ta(le for t%e operating system* so it could reveal different values on different platforms for c%aracters it% an AS$II value of 679 or %ig%er. -%is may or may not (e useful. -%e ord function returns t%e numeric value of t%e first c%aracter of @X#G* or NY if @X#G is not specified. -%e value is returned according to t%e AS$II ta(le and is al ays unsigned. -%us* using t%e t o functions toget%er* printc%r1ord10(022K e s%ould get t%e c%aracter X(F. ,.3.1.6 Rando- Nu-bers
351 Sree Sakthi Engineering College

#erl provides a (uilt)in random num(er generator. All random num(ers need a XseedF value* %ic% is used in an algorit%m* usually (ased on t%e precision* or lac+ t%ereof* for a specific calculation. -%e format for t%e rand function is rand @X#G rand -%e function returns a floating)point random num(er (et een : and @X#G or (et een : and 6 1including :* (ut not including 62 if @X#G is not specified. If you ant an integer random num(er* 4ust use t%e int function to return a reasona(le value* as in t%is e'ample: printint1rand16B22*3Zn3K 8ou can use t%e srand function to seed t%e random num(er generator it% a specific value: srand @X#G -%e rand function automatically calls t%e srand function t%e first time rand is called* if you donMt specifically seed t%e random num(er generator. -%e follo ing program calculates t%e num(er of random num(ers generated (efore a duplicate value is returned: my ;randresK my Ncounter ) 6K srand11time12 f 1time12 ; NR22 f e'p1lengt%1N:22WWNN2K %ile 1my Nval) rand122 ^ last if 1defined1Nrandres^Nval`22K print 3$urrent count is NcounterZn3 if 11Ncounter ;6::::2 )) :2K Nrandres^Nval` ) 6K NcounterIIK ` print 3Out of Ncounter tries I encountered a duplicate random num(erZn3K
352 Sree Sakthi Engineering College

,.3.#. Wor&in( with Strin(s ,.3.#.1 Strin( Concatenation 4ethod 1 8 usin( !er"+s dot operator $oncatenating strings in #erl is very easy. -%ere are at least t o ays to do it easily. One ay to do it ) t%e ay I normally do it ) is to use t%e 3dot3 operator 1i.e.* t%e decimal c%aracter2. -%e simple e'ample s%o n (elo demonstrates %o you can use t%e dot operator to merge* or concatenate* strings. /or simplicity in t%is e'ample* assume t%at t%e varia(le Nname is assigned t%e value 3c%ec+(oo+3. Ne't* you ant to pre)pend t%e directory 3Ctmp3 to t%e (eginning of t%e filename* and t%e filename e'tension 3.tmp3 to t%e end of Nname. Jere0s t%e code t%at creates t%e varia(le Nfilename: Nname V 3c%ec+(oo+3K Nfilename V 3CtmpC3 . Nname . 3.tmp3K S Nfilename no contains 3CtmpCc%ec+(oo+.tmp3 4ethod # 8 usin( !er"+s Coin function A second ay to create t%e desired varia(le Nfilename is to use t%e 4oin function. 5it% t%e 4oin function* you can merge as many strings toget%er as you li+e* and you can specify %at to+en you ant to use to separate eac% string. -%e code s%o n in Listing 7 (elo uses t%e #erl 4oin function to ac%ieve t%e same result as t%e code s%o n in Listing 6: Nname V 3c%ec+(oo+3K Nfilename V 4oin 33* 3CtmpC3* Nname* 3.tmp3K S Nfilename no contains 3CtmpCc%ec+(oo+.tmp ,.3.#.# Strin( 2en(th -o get t%e lengt% of a string in #erl* use t%e #erl lengt% function on your string* li+e t%is: Nsi.e V lengt% NlastYnameK
353 Sree Sakthi Engineering College

-%e varia(le Nsi.e ill no contain t%e string lengt%* i.e.* t%e num(er of c%aracters in t%e varia(le named NlastYname. 0=a-p"e Jere0s a more complete script to demonstrate t%is #erl string lengt% tec%ni,ue: Na V 3foo* (ar* and (a.3K print lengt% NaK 5%en t%at little script is run t%roug% t%e #erl interpreter it ill print t%e num(er 6E* %ic% is t%e lengt% of t%at string 1i.e.* t%e num(er of c%aracters in t%e #erl string2. ,.3.#.$ Case 4odifications -%e four (asic functions are lc* uc* lcfirst* and ucfirst. -%ey convert a stringto all lo ercase* all uppercase* or only t%e first c%aracter of t%e string to lo ercase oruppercase* respectively. /or @'ample: Nstring V 3-%e $at Sat on t%e "at3K printlc1Nstring2 S Outputs 0t%e cat sat on t%e mat0 printlcfirst1Nstring2 S Outputs 0t%e $at Sat on t%e "at0 printuc1Nstring2 S Outputs 0-J@ $A- SA- ON -J@ "A-0 printucfirst1Nstring2 S Outputs 0-%e $at Sat on t%e "at0 -%ese functions can (e useful for Xnormali.ingF a string into an all uppercase or lo ercase formatauseful %en com(ining and de)duping lists %en using %as%es. ,.3.#.' 0nd8of82ine Character Re-o%a" -%e c%op function can (e used to strip t%e last c%aracter off any e'pression %ile1T/JP2 ^ c%opK ... `
354 Sree Sakthi Engineering College

,.3.#., Strin( 2ocation -%e inde'12 function is used to determine t%e position of a letter or a su(string in a string. /or e'ample* in t%e ord 3frog3 t%e letter 3f3 is in position :* t%e 3r3 in position 6* t%e 3o3 in 7 and t%e 3g3 in =. -%e su(string 3ro3 is in position 6. &epending on %at you are trying to ac%ieve* t%e inde'12 function may (e faster or more easy to understand t%an using a regular e'pression or t%e split12 function. @'ample: SbCusrC(inCperl use strictK use arningsK my Nstring V 0perlmeme.org0K my Nc%ar V 0l0K my Nresult V inde'1Nstring* Nc%ar2K print 3Gesult: NresultZn3K Instead of looping t%roug% every occurrence of a letter in a string to find t%e last one* you can use t%e rinde'12 function. -%is or+s e'actly t%e same as inde'12 (ut it starts at t%e end of t%e string. -%e inde' value returned is string from t%e start of t%e string t%oug%. @'ample: SbCusrC(inCperl use strictK use arningsK my Nstring V 0perlmeme.org0K my Nc%ar V 0e0K my Nresult V rinde'1Nstring* Nc%ar2K print 3Gesult: NresultZn3 ,.3.#./ 0=tractin( Substrin(s -%e su(str12 function is used to return a su(string from t%e e'pression supplied as it0s first argument. -%e function is a good illustration of some of t%e ays in %ic% #erl is different from
355 Sree Sakthi Engineering College

ot%er languages you may %ave used. su(str12 %as a varia(le num(er of arguments* it can (e told to start at an offset from eit%er end of t%e e'pression* you can supply a replacement string so t%at it replaces part of t%e e'pression as ell as returning it* and it can (e assigned tob. @'ample: SbCusrC(inCperl use strictK use arningsK my Nstring V 0No is t%e time for all good people to come to t%e aid of t%eir party0K my Nfragment V su(str Nstring* >K print 3 string: TNstringPZn3K print 3fragment: TNfragmentPZn3K ,.3.#.1 Stac&s One of t%e most (asic uses for an array is as a stac+. If you consider t%at an array is a list of individual scalars* it s%ould (e possi(le to treat it as if it ere a stac+ of papers.Inde' : of t%e array is t%e (ottom of t%e stac+* and t%e last element is t%e top. 8ou canput ne pieces of paper on t%e top of t%e stac+ 1pus%2* or put t%em at t%e (ottom1uns%ift2. 8ou can also ta+e papers off t%e top 1pop2 or (ottom 1s%ift2 of t%e stac+. !ush and !op In perl stac+s are easy to (e implemented. Stac+s %ic% follo s LI/O 1Last In /irst Out2 data structure can (e %andled in perl it% 0#O#0 and 0#USJ0 +ey ords. !O! 0=a-p"e@ my Nstr-est#O#1Uarr-est2K print 3Nstr-est3K In t%is e'ample t%e Last element present in Uarr-est ill (e poped and ill (e assigned to varia(le Nstr-est 1LI/O2. Suppose t%e array contains value 3S-AG3 at it0s last position t%us t%e ne't line of t%e code ill populate S-AG. !US> 0=a-p"e@ #USJ1Uarr-est Nstr-est2 if 1Nstr-est2K In t%is e'ample e are pus%ing Nstr-est varia(le to t%e array Uarr-est. After t%e #USJ
356 Sree Sakthi Engineering College

statement t%e array si.e ill (e increased (y one and t%e last element of t%e array ill (e t%e value contained in varia(le Nstr-est. Shift *nd Unshift@ -%e s%ift function returns t%e first value in an array* deleting it and s%ifting t%eelements of t%e array list to t%e left (y one. 3.#.3 Sp"icin( *rra)s #erl0s splice12 function is used to cut out and return a c%un+ or portion of an array. -%e portion t%at is cut out starts at t%e O//S@- element of t%e array and continues for L@NG-J elements. If t%e L@NG-J is not specified* it ill cut to t%e end of t%e array. 0=a-p"e@ UmyNames V 10Laco(0* 0"ic%ael0* 0Los%ua0* 0"att%e 0* 0@t%an0* 0Andre 02K UsomeNames V splice1UmyNames* 6* =2K

Loin@ #erl0s 4oin12 function is used to connect all t%e elements of a specific list or array into a single string it% t%e LOIN@G e'pression. -%e list is concatenated into one string it% t%e element contained in t%e LOIN@G varia(le in (et een eac% item. Synta': NS-GING V 4oin1LOIN@G* ULIS-2K 0=a-p"e@ UmyNames V 10Laco(0* 0"ic%ael0* 0Los%ua0* 0"att%e 02K NsomeNames V 4oin10* 0* UmyNames2K -%in+ of t%e UmyNames array as a ro of num(ered (o'es* eac% it% a name in it. -%e 4oin12 function ould ta+e all of t%e content in t%ose (o'es in t%e UmyNames array and connect t%em toget%er it% a comma and a space. -%e value of UsomeNames t%en (ecomes 3Laco(* "ic%ael* Los%ua* "att%e 3. -%e list of names is concatenated* or 4oined* (y commas. sp"it@
357 Sree Sakthi Engineering College

#erl0s split12 function is used to (rea+ a string into an array on a specific pattern. -%e #A--@GN is a regular e'pression t%at can (e as simple as a single c%aracter. ?y default t%e S-GING is split on every instance of t%e #A--@GN* (ut you can LI"I- it to a specific num(er of instances. S)nta=@ ULIS- V split1C#A--@GNC* S-GING* LI"I-2K 0=a-p"e@ NmyNames V 3Laco(*"ic%ael*Los%ua*"att%e *@t%an*Andre 3K UnameList V split1C*C* NmyNames2K In t%e a(ove e'ample* t%e split function ta+es a plain string of names* separated (y commas. It t%en (rea+s t%e string apart on eac% instance of t%e comma* putting t%e results into t%e array UnameList. -%e value of UnameList ould t%en (e: UmyNames V 10Laco(0* 0"ic%ael0* 0Los%ua0* 0"att%e 0* 0@t%an0* 0Andre 02K ?y using t%e LI"I- option* you can split t%e array into a specific si.e. /or e'ample: NmyNames V 3Laco(*"ic%ael*Los%ua*"att%e *@t%an*Andre 3K UnameList V split1C*C* NmyNames* =2K -%is ould split t%e array into = c%un+s* so t%e value of UnameList ould t%en (e: UmyNames V 10Laco(0* 0"ic%ael0* 0Los%ua*"att%e *@t%an*Andre 02K (rep@ #erl0s grep12 function runs a regular e'pression on eac% element of an array* and returns only t%e elements t%at evaluate to true. Using regular e'pressions can (e e'tremely po erful and comple'. 8ou can find out more a(out t%em in t%e regular e'pressions topic. S)nta=@ ULIS- V grep1@X#G@SSION* UAGGA82K 0=a-p"e@ UmyNames V 10Laco(0* 0"ic%ael0* 0Los%ua0* 0"att%e 0* 0Ale'ander0* 0Andre 02K UgrepNames V grep1CfAC* UmyNames2K
358 Sree Sakthi Engineering College

-%in+ of t%e UmyNames array as a ro of num(ered (o'es* going from left to rig%t* num(ered starting it% a .ero. -%e grep12 function goes t%roug% eac% of t%e elements 1(o'es2 in t%e array* and compares t%eir contents to t%e regular e'pression. If t%e result is true* t%e contents are t%en added to t%e ne UgrepNames array. In t%e a(ove e'ample* t%e regular e'pression is loo+ing for any value t%at starts it% a capital A. After sifting t%roug% t%e contents of t%e UmyNames array* t%e value of UgrepNames (ecomes 10Ale'ander0* 0Andre 02. One ,uic+ ay to ma+e t%is particular function more po erful is to reverse t%e regular e'pression it% t%e NO- operator. -%e regular e'pression t%en loo+s for elements t%at evaluate to false and moves t%em into t%e ne array. UmyNames V 10Laco(0* 0"ic%ael0* 0Los%ua0* 0"att%e 0* 0Ale'ander0* 0Andre 02K UgrepNames V grep1bCfAC* UmyNames2K In t%e a(ove e'ample* t%e regular e'pression is loo+ing for any value t%at does not start it% a capital A. After sifting t%roug% t%e contents of t%e UmyNames array* t%e value of UgrepNames (ecomes 10Laco(0* 0"ic%ael0* 0Los%ua0* 0"att%e 02. -ap@ #erl0s map12 function runs an e'pression on eac% element of an array* and returns a ne array it% t%e results. S)nta=@ ULIS- V map1@X#G@SSION* UAGGA82K 0=a-p"e UmyNames V 104aco(0* 0ale'ander0* 0et%an0* 0andre 02K UucNames V map1ucfirst* UmyNames2K -%in+ of t%e UmyNames array as a ro of num(ered (o'es* going from left to rig%t* num(ered starting it% a .ero. -%e map12 function goes t%roug% eac% of t%e elements 1(o'es2 in t%e array* and runs t%e @X#G@SSION on t%eir contents. -%e altered contents are t%en added to t%e ne UucNames array.

359 Sree Sakthi Engineering College

In t%e a(ove e'ample* @X#G@SSION is t%e (uilt)in function ucfirst t%at ma+es t%e first letter of t%e ord upper case. After running t%e e'pression on eac% element of t%e UmyNames array* t%e value of UucNames (ecomes 10Laco(0* 0Ale'ander0* 0@t%an0* 0Andre 02. sort@ 5it% any list* it can (e useful to sort t%e contents. &oing t%is manually is a comple' process* so #erl provides a (uilt)in function t%at ta+es a list and returns a le'ically sorted version. S)nta=@ sort UarrayK 0=a-p"e@ Or to specify an e'plicit le'ical su(routine: sort ^ Na cmp N( ` UarrayK re%erse@ #erl0s reverse12 function is used to reverse t%e order of an array. It s%ould (e noted t%at t%e function returns a reversed array (ut does not actually reverse t%e array passed into t%e function. S)nta=@ UG@]@GS@&YLIS- V reverse1UAGGA82K 0=a-p"e@ UmyNames V 10Laco(0* 0"ic%ael0* 0@t%an0* 0Andre 02K UreversedNames V reverse1UmyNames2K -%in+ of t%e UmyNames array as a ro of num(ered (o'es* going from left to rig%t* num(ered starting it% a .ero. -%e reverse12 function ould copy t%e contents of t%e (o'es from t%e UmyNames array into t%e UreversedNames array* %ile reversing t%eir order. -%e value of UreversedNames t%en (ecomes 10Andre 0* 0@t%an0* 0"ic%ael0* 0Laco(02* and UmyNames remains t%e same. ,.3.$ Re(u"ar 0=pressions Gegular e'pressions are very po erful tools for matc%ing* searc%ing* and replacing te't. Unfortunately* t%ey are also very o(tuse. It does not %elp t%at most e'planations of regular e'pressions start from t%e specification.
360 Sree Sakthi Engineering College

A regular e'pression is a string of c%aracters t%at define t%e pattern or patterns you are vie ing. -%e synta' of regular e'pressions in #erl is very similar to %at you ill find it%in ot%er regular e'pression. ,.3.$.1 !attern 4odifiers #attern "odifiers c%ange t%e (e%avior of t%e individual operator. 4odifier
Ti Ts Tm T2 To

4eanin( Ignore alp%a(etic case distinctions 1case insensitive2. Let -matc% ne line and ignore deprecated QF varia(le. Let ] and Q matc% ne't to em(edded Un. Ignore 1most2 %itespace and permit comments in pattern. $ompile pattern once only.

-%e Ci modifier says to matc% (ot% upper) and lo ercase 1and title case* under Unicode2. -%e Cs and Cm modifiers don0t involve anyt%ing +in+y. Gat%er* t%ey affect %o #erl treats matc%es against a string t%at contains ne lines. ?ut t%ey aren0t a(out %et%er your string actually contains ne lines. -%e Cm modifier c%anges t%e interpretation of t%e f and N metac%aracters (y letting t%em matc% ne't to ne lines it%in t%e string instead of considering only t%e ends of t%e string. -%e Co modifier controls pattern recompilation. -%e C' is t%e expressive modifier: it allo s you to exploit %itespace and explanatory comments in order to expand your pattern0s legi(ility* even extending t%e pattern across ne line (oundaries. ,.3.$.# The 4atch Operator -%e matc% operator* mCC* is used to matc% a string or statement to a regular e'pression. /or e'ample* to matc% t%e c%aracter se,uence 3foo3 against t%e scalar N(ar* you mig%t use a statement li+e t%is: if 1N(ar VO CfooC2

361 Sree Sakthi Engineering College

-%e mCC actually or+s in t%e same fas%ion as t%e ,CC operator series.you can use any com(ination of naturally matc%ing c%aracters to act as delimiters for t%e e'pression. /or e'ample* m^`* m12* and mPT are all valid. 8ou can omit t%e m from mCC if t%e delimiters are for ard slas%es* (ut for all ot%er delimiters you must use t%e m prefi'. Note t%at t%e entire matc% e'pression.t%at is t%e e'pression on t%e left of VO or bO and t%e matc% operator* returns true 1in a scalar conte't2 if t%e e'pression matc%es. -%erefore t%e statement: Ntrue V 1Nfoo VO mCfooC2K 5ill set Ntrue to 6 if Nfoo matc%es t%e rege'* or : if t%e matc% fails. In a list conte't* t%e matc% returns t%e contents of any grouped e'pressions. /or e'ample* %en e'tracting t%e %ours* minutes* and seconds from a time string* e can use: my 1N%ours* Nminutes* Nseconds2 V 1Ntime VO mC1ZdI2:1ZdI2:1ZdI2C2K 4atch Operator 4odifiers -%e matc% operator supports its o n set of modifiers. -%e Cg modifier allo s for glo(al matc%ing. -%e Ci modifier ill ma+e t%e matc% case insensitive. Jere is t%e complete list of modifiers 4odifierDescription i "a+es t%e matc% case insensitive m Specifies t%at if t%e string %as ne line or carriage return c%aracters* t%e f and N operators ill no matc% against a ne line (oundary* instead of astring (oundary o @valuates t%e e'pression only once s Allo s use of . to matc% a ne line c%aracter ' Allo s you to use %ite space in t%e e'pression for clarity g Glo(ally finds all matc%es cg Allo s t%e searc% to continue even after a glo(al matc% fails 4atchin( On") Once -%ere is also a simpler version of t%e matc% operator ) t%e A#A--@GNA operator. -%is is (asically identical to t%e mCC operator e'cept t%at it only matc%es once it%in t%e string you are searc%ing (et een eac% call to reset.
362 Sree Sakthi Engineering College

/or e'ample* you can use t%is to get t%e first and last elements it%in a list: SbCusrC(inCperl Ulist V , Cfood foos(all su(eo footnote terfootcanicfoot(rdigeCK
foreac% 1Ulist2 ^ Nfirst V N6 if A1foo.W2AK Nlast V N6 if C1foo.W2CK `

print 3/irst: Nfirst* Last: NlastZn3K -%is ill produce follo ing result /irst: food* Last: foot(rdige The Substitution Operator -%e su(stitution operator* sCCC* is really 4ust an e'tension of t%e matc% operator t%at allo s you to replace t%e te't matc%ed it% some ne te't. -%e (asic form of t%e operator is: sC#A--@GNCG@#LA$@"@N-CK -%e #A--@GN is t%e regular e'pression for t%e te't t%at e are loo+ing for. -%e G@#LA$@"@N- is a specification for t%e te't or regular e'pression t%at e ant to use to replace t%e found te't it%. /or e'ample* e can replace all occurrences of .dog. it% .cat. using Nstring VO sCdogCcatCK @'ample: SCuserC(inCperl Nstring V 0-%e cat sat on t%e mat0K Nstring VO sCcatCdogCK print 3/inal Gesult is NstringZn3K -%is ill produce follo ing result -%e dog sat on t%e mat ,.3.$.$ The Substitution Operator Jere is t%e list of all modifiers used it% su(stitution operator 4odifierDescription i "a+es t%e matc% case insensitive
363 Sree Sakthi Engineering College

o s ' g e

Specifies t%at if t%e string %as ne line or carriage return c%aracters* t%e f and N operators ill no matc% against a ne line (oundary* instead of a string (oundary @valuates t%e e'pression only once Allo s use of . to matc% a ne line c%aracter Allo s you to use %ite space in t%e e'pression for clarity Geplaces all occurrences of t%e found e'pression it% t%e replacement te't @valuates t%e replacement as if it ere a #erl statement* and uses its return value as t%e replacement te't

,.3.$.' Trans"ation -ranslation is similar* (ut not identical* to t%e principles of su(stitution* (ut unli+e su(stitution* translation 1or transliteration2 does not use regular e'pressions for its searc% on replacement values. -%e translation operators are: trCS@AG$JLIS-CG@#LA$@"@N-LIS-Ccds yCS@AG$JLIS-CG@#LA$@"@N-LIS-Ccds -%e translation replaces all occurrences of t%e c%aracters in S@AG$JLIS- it% t%e corresponding c%aracters in G@#LA$@"@N-LIS-. /or e'ample* using t%e 3-%e cat sat on t%e mat.3 string e %ave (een using in t%is c%apter: SCuserC(inCperl Nstring V 0-%e cat sat on t%e mat0K Nstring VO trCaCoCK print 3NstringZn3K -%is ill produce follo ing result -%e cot sot on t%e mot. Standard #erl ranges can also (e used* allo ing you to specify ranges of c%aracters eit%er (y letter or numerical value. -o c%ange t%e case of t%e string* you mig%t use follo ing synta' in place of t%e uc function.
364 Sree Sakthi Engineering College

S-ar putea să vă placă și