Sunteți pe pagina 1din 47

PerlTutorial PabloManalastas<pmanalastas@ateneo.

edu>

LEARNINGPERL

Numbers

Numbersaredoubleprecisionfloatingpoint values(doubleinC) 3,1.5,2.7e8,2_427_132_115, 0577,0xf3ab,0b1110001011 Numericoperations Add(+),subtract(),negate(),multiply(*), divide(/),modulus(%) 3+4.2,2.3e4*6.2523,10%4

Strings

Canbeanylength&cancontainanycharacters Singlequotedstrings 'PablodeGracia,Jr.' 'Thewinterofourdiscontent.' 'Queen\'sJewels' #thesinglequote'isspecifiedas\' 'Thebackslash\\isspecial' #thebackslash\isspecifiedas\\

Strings

Doublequotedstrings againstearth'sflowingbreast Iamcalled\handsome\bysome Icame.\nIsaw.\nIconquered.\n Tab\tseparated\tentries\there Stringconcatenation Hello.world\n Stringrepetition magandax3

Autoconversion:Numbers&Strings

Arithmeticoperations(+,,*,/,%)convertstrings tonumbers 12plus2+3#givesthenumber15 Stringoperation(.)convertsnumberstostrings XJW.24*5#givesthestringXJW120

Variables

Variablenames [$@%][AZaz_][09AZaz_]* Scalarvariables,namestartswith$


Holdsonevalue(scalarvalue) Examples: $daily_rate=350.00; $horse_name=Heaven'sPride; $monthly_pay=$daily_rate*22;

BinaryAssignmentOperators

Replace $var=$varop$val; by $varop=$val; Examples: $new_rate+=12; $quotient/=10; $name.=,PhD; $balance=$withdrawal;

OutputUsingprint

Writeoutputtostdoutusingprint printHello,world!\n; printTheansweris.350*6. \n; printTheansweris,350*6, \n;

Interpolation

Interpolation:thereplacementofascalar variablebyitsvalueinadoublequotedstringor whenoccuringalone Examples $meal='beefsteak'; printJuanate$meal\n; printIlike$mealfordinner\n; printJuan'sdinneris.$meal; printJuan'sdinneris,$meal;

DelimitingtheVariableName

Use{}todelimitthevariablenametobe interpolated Examples $what='steak'; printIloveallkindsof${what}s\n; printIloveallkindsof$what,s\n; printPrimeribisthe$whatof${what}s\n;

ComparisonOperators

Numericcomparisonoperators ==,!=,<,>,<=,>= Examples: 50==100/2; #true 100/3!=33.3 #true Stringcomparisonoperators eq,ne,lt,gt,le,ge 'pedro'lt'jose' #false 'jose'eqjose #true ''gt'' #true

BooleanValues

undef,numberzero(0),stringzero('0'),the emptystring(''),areallfalse.Undefdesignates avariablewithnovalueassignedyet. nonzeronumbers(like1)andnonempty strings(except'0')arealltrue. Examples $bool1='Fred'lt'fred'; $bool2='fred'lt'Fred'; print$bool1;#prints1fortrue print$bool2;#emptystringforfalse

IfControlStructure

Syntax if(condition){truepart;}else{falsepart;} Example $disc=$b*$b4.0*$a*$c; if($disc>=0.0){ printRealroots\n; }else{ printComplexroots\n; }

ReadingOneLinefromStdin

Use<STDIN>toreadonelinefromstandard input,usuallytheconsolekeyboard Examples: printEnterfirstname:; $fname=<STDIN>; printEnterlastname:; $lname=<STDIN>; chomp($fname); chomp($lname); printYourname:$fname$lname\n;

Thechomp()Function

chomp()removesatrailingnewline'\n'fromthe stringvalueofavariable Version2ofprogram: printEnterfirstname:; chomp($fname=<STDIN>); printEnterlastname:; chomp($lname=<STDIN>); printYourname:$fname$lname\n;

WhileControlStructure

Syntax: initialization; while(condition){ statements; reinitialization; }

Example: $i=1; while($i<=10){ printCounting$i\n; ++$i; }

UNDEF

Ifanundefinedvariableisusedasanumber, undefislikezero(0).Ifusedasastring,undef isliketheemptystring('') If$xisundefined,thefollowingareallowed: $x+=2; $x.='bye'; If$xhasavalue,then $x=undef; makes$xundefined

Thedefined()Function

The<STDIN>operationmayreturnthevalue undefwhenthereisnomoreinput,suchasat endoffile Thefunctiondefined()cantestif<STDIN>read onelineofinputfromstandardinput. Example while(defined($line=<STDIN>)){ printYoutyped:$line; } printNomoreinput\n;

Exercises

WriteaPerlprogramthatreadslinesofinput from<STDIN>,andprintseachlineread.Stop whenthelinethatisreadis'Done'(withoutthe quotes). WriteaPerlprogramthatreadsthevaluesof threevariables$num1,$oper,and$num2from <STDIN>.Ifthevalueof$operisoneofthe strings'plus','minus','times',or'over',the programshouldcarryouttheindicated operationon$num1and$num2.

Lists&Arrays

List:anorderedcollectionofscalarvalues.The indexisthepositionofascalarvalueinthelist. Theindexrunsfrom0to(n1),wherenisthe sizeofthelist.Anarrayisavariablethat containsalist,andstartswitha@sign Example: @quals @friends

InitializingArrayswithLiteralValues

Anarraymaybeinitializedwithvaluesin parentheses().Example: @propty=('Pablo',62,'male', undef); Here,thearrayis@propty,andthevaluesin thelistare: $propty[0]is'Pablo' $propty[1]is62 $propty[2]is'male' $propty[3]isundef#civilstatus

ValuesMayAllBeSameType

Alllistvaluesmaybethesametype @friends=('Pablo','Jose', 'Juan','Mario','David'); Here,thearrayis@friends,andthevaluesin thelistare: $friends[0]is'Pablo' $friends[1]is'Jose' $friends[2]is'Juan' $friends[3]is'Mario' $friends[4]is'David'

ValuesofArrayIndices

Anyvalue,variable,orexpression,whosevalueis integerorcanbeconvertedtointegercanbeusedas index. Example: $ndx=2.5; $friends[$ndx+1]is$friends[3] $#friendsisthevalueofthelastindexofarray @friends,whichis4. $friends[$#friends+10]='Carlos'; addselement'Carlos'atindex14,the15thelement. Valuesatindex5to13willbeundef.

InitializingArraywithLiteralValues

@arr=(); @arr=(5..10,17,21); @arr=($a..$b); @arr=qw/PabloJoseMario/; @arr=qw!PabloJoseMario!; @arr=qw(PabloJoseMario); @arr=qw{PabloJoseMario}; @arr=qw<PabloJoseMario>;

InterpolateArrays/ValuesinStrings

If@arrisanarray,thenarray@arrandlist value$arr[k]willbeinterpolated(evaluated) whenplacedinsidedoublequotedstrings Exampleinterpolatingarrays @arr=(5..7); printFour@arreight\n; #willprintFour567eight Exampleinterpolatinglistvalues @toy=('toycar','toyrobot', 'toygun'); printIhavea$toy[2]athome\n;

pop()Function

pop()removestherightmostlistvaluefroman array Example: @stk=(5..9); $a=pop(@stk); #remove9leaving5..8,$a=9 $b=pop@stk; #remove8leaving5..7,$b=8 pop@stk;#remove7leaving5..6

push()Function

push():addsnewrightmostvaluestothelistof anarray Example: @stk=(5..8); push(@stk,0);#now(5,6,7,8,0) push@stk,(1..3);#now(5,6,7,8,0,1,2,3) @stk2=qw/101112/; push@stk,@stk2; #now(5,6,7,8,0,1,2,3,10,11,12)

shift()andunshift()

shift()islikepushingnewfirstvalues,unshift() islikepoppingthefirstvalue.Theseoperations aredoneontheleftmostendofthearray. @stk=(5..9); shift(@stk,4);#now(4..9) shift@stk,(1..3);#now(1..9) $a=unshift@stk; #remove1leaving(2..9),$a=1

foreachControlStructure

Syntax:foreach$var(@arr){body;} Example:formthepuralformofeachfruit: @fruits=qw/mangobananadurian/; foreach$fr(@fruits){ $fr.='s'; } print@fruits\n;

Perl'sDefaultVariable:$_

Ifyouomit$varinaforeachloop,youcanrefer tothisvariableusing$_ foreach(1..10){ $sum+=$_; } printTotalof1..10is$sum\n; Ifyouomit$varinaprintstatement,thevalueof $_willbeprinted. $_=TodayisSaturday\n; print;

reverse()andsort()

reverse(@arr)reversestheorderofvaluesin thelist @fruits=qw/mangopapayachico/; @revfr=reverse(@fruits); @fruits=reverse(@fruits); sort(@arr)sortsthevaluesinthelistin increasinglexicographicorder,orstringorder, notnumericorder @fruits=qw/mangopapayachico/; @sfruits=sort(@fruits); @rfruits=reversesort@fruits;

Forcingscalar()Context

Ifyouwanttouseanarray@arrinascalar context(forexample,getthenumberof elementsinthelist),usethefunctionscalar() @fruits=qw/mangobananaorange/; printFavoritefruits:@fruits\n; printMyfavoritefruitsare, scalar(@fruits),inall\n;

<STDIN>asListorScalar

$line=<STDIN>; readsonelinefrom<STDIN> @lines=<STDIN>; readstheentirefile<STDIN>untilendoffile andassignseachlineasanelementofthe array@lines.Iffileisbig,@linesmayuseupa hugeamountofmemory.Theendoffileof <STDIN>isindicatedbytypingControlDin Unix.

SortingLinesfrom<STDIN>

chomp(@lines=<STDIN>); @lines=sort@lines; foreach$line(@lines){ print$line\n; } print**Nomore**;

Exercises

Writeaprogramthatreadsfrom<STDIN>aset ofnumericvalues,oneperline,andcomputes themeanandvarianceofthesevalues.IfNis thenumberofvalues,then mean=(sumofallvalues)/N; variance= (sumsquare(eachvaluemean))/N; Writeaprogramthatreadslinesfrom<STDIN>, sortstheselinesinreversealphabeticalorder, printsthelines,andprintsthetotalnumberof lines.

Hashes

Ahashisalistofkeyvaluepairs.Thevariable namestartswith% %age=(Pablo,62,Karen,23, Paul,33); HerethekeyPablohasvalue62,thekey Karenhasvalue23,andthekeyPaulhas value33. Accessingahashbykey $age{Paul}gives33 $age{Karen}gives23

Hashes:BigArrowNotation

%lname=(Pablo=>Manalastas, Rojo=>Sanchez, Joy=>Fernando); %month=(1=>January, 2=>February, 3=>March,4=>April,5=>May); $lname{Rojo}givesSanchez $month{4}givesApril

UsingaHash

%lname=(Pablo=>Manalastas, Rojo=>Sanchez, Joy=>Fernando); printEnterfirstname:; chomp($fname=<STDIN>); printLastnameof$fnameis, $lname{$fname},\n;

Keys&Values

%month=(1=>January, 2=>February, 3=>March,4=>April,5=>May); @k=keys%month; #@kisthearrayofkeysonly @v=values%month; #@visthearrayofvaluesonly

each()&exists()

%month=(1=>January, 2=>February, 3=>March,4=>April,5=>May); Toaccesseach(key,value)pair: while(($key,$val)=each%month){ print$key=>$val\n; } Tocheckifavalueexistsforakey If(exists$month{13}){ printThatis$month{13}\n; }

HashElementInterpolation

%month=(1=>January, 2=>February, 3=>March,4=>April,5=>May); Caninterpolateeachelement printFirstmonthis$month{1}\n; Notallowed printThemonthsare:%month\n;

Exercises

Writeaprogramthatreadsaseriesofwords (withonewordperline)untilendofinput,then printsasummaryofhowmanytimeseachword wasseen. Writeaprogramthatpromptsformonthnumber (112),daynumber(131),andyear(1900 2008),anddisplaytheinputsintheform MonthNameday,year(withoutthequotes).

Subroutines

Userdefinedfunctionsthatallowthe programmertoreusethesamecodemany timesinhisprogram Subroutinenamestartswith&,ingeneral Definingasubroutine subsubName{ subBody; }

ExampleFunction

Definingafunction: subgreet{ printHello!\n; }

Usingthefunction: &greet;

PassingArguments

Ifthesubroutineinvocationisfollowedbyalistwithin parenthesis,thelistisassignedtospecialvariable@_ withinthefunction Example &greet(Pablo,Jose,Maria); Youcanusetheargumentsasfollows: subgreet{ foreach$namein(@_){ printHello$name!\n: } }

LocalVariables;ReturningValues

subsum{ local($total); $total=0; foreach$numin(@_){ $total+=$num; } $total; }

Exercises

Writeafunctionthatreturnstheproductofits arguments Writeafunctionthatacceptstwoargumentsn andd,returnsalistoftwonumbersqandr, whereqisthequotientofnandd,andristheir remainder Writeafunctionthat,givenanynumbernas argument,printsthevalueofthatnumberin words,asinacheckwriter.

S-ar putea să vă placă și