You are on page 1of 2

Perl Reference Card

This is version 2 of the perl reference card. (cl) 2008 Michael Goerz <goerz@physik.fu-berlin.de>. http://www.physik.fu-berlin.de/~goerz/ Information taken liberally from the perl doc mentation and vario s other so rces. !o may freely distrib te this doc ment.

1.! "as#es
1h%(k2$%>$(#.l2*'kD$%>$H ! $#.l$%$$m.pAk2B! @.$%$1h! 1h$%$@.! fore.ch$$k$(keys(1h A..B fore.ch$$#$(#.ls(1h A..B while$(($k'$# %e.ch$1h A..B delete$$hAk2B! e+ists$$hAk2B defined$$hAk2B hash initialization recall val e array of keys and val es create hash from array iterate over list of keys iterate over list of val es iterate over key'val e'pairs delete key does key e%ist, is key defined,

( System )nteraction
system((c.t$$fRsort$-u>$f.s* ! system call @.$%$re.dpipe((lsmod* ! catch o tp t $tod.y$%$(;od.y:$(.Sd.teS! catch o tp t chroot((/home/user/* ! chan"e root while$(<O.c> $AB operate on all c'files unlink((/tmp/file* ! delete file if$(-f$(file.t+t* A...B file test File Tests: -r'$-w readable& $riteable -+ e%ec table -e e%ists -f'$-d'$-l is file& directory& symlink -;'$-T te%t file& binary file -U'$-/ mod)access a"e in days @st.ts$%$st.t((filen.me* ! *-'element list $ith stat s More: chmod'$chown'$chroot'$fcntl'$glob'$ioctl'$link'$ lst.t'$mkdir'$opendir'$re.dlink'$ren.me'$rmdir'$ symlink'$um.sk'$utime

1 Variable Types
1.1 Scalars and Strings
chomp($str ! discard trailin" "n $#$%$chop($str ! #v becomes trailin" char e&'$ne'$lt'$gt'$le'$ge'$cmp strin" comparison $str$%$()*$+$,! $str is no$ ())))* $#$%$inde+($str'$$+ !$ find inde% of $+ in $str& $#$%$rinde+($str'$$+ ! startin" from left or ri"ht $#$%$substr($str'$$strt'$$len ! e%tract s bstrin" $cnt$%$$sky$%~$tr/)--//! co nt the di"its in$$sky $str$%~$tr/.-z/-0/$/cs! chan"e non'alphas to space $#$%$sprintf((12)s$1)3d*'$s'$n ! format strin" Format String: %4fl.gs54)54width54.precision54mod5type types( c character d(i si"ned decimal int e(6 scientific notation f decimal floatin" point g'$7 shorter 1e or 1f$/$16 or 1f o si"ned octal s strin" of chars u'$+'$8 nsi"ned decimal int ) he% int ) he% int in caps p address pointer n nothin" printed modifiers( h'l'9 ar" is short int ) lon" int& do ble) lon" do ble More: chr'$crypt'$he+'$lc'$lcfirst'$length'$oct'$ord'$ p.ck'$&/:;<=>7/'$&&/:;<=>7/'$re#erse'$uc'$ucfirst

2 $asic Synta%
($.'$$b $%$shift(@/<7I ! sub$pAmy$$#.r$%$shift!$...B p((bl.* ! if(e+pr AB$elsif$AB$else$AB unless$(e+pr AB while$(e+pr AB until$(e+pr AB do$AB$until$(e+pr for($i%2!$$i<%2)!$$iJJ AB fore.ch$$i$(@list AB l.st'$ne+t'$redo e#.l$A$.%$./$b!$B!$ $w.rn$$@$if$$@! read command line params define s bro tine e%ec te s bro tine conditional ne"ative conditional $hile'loop ntil'loop postcheck ntil'loop for'loop foreach'loop end loop& skip to ne%t& + mp to top e%ception handlin"

* )np't+,'tp't
open(=>V=96'Kin.t+tK $or$die! open file for inp t open(=>V=96'K<:utf3K'KfileK ! open file $ith encodin" open(;UL'$KJ>K'$undef ! open anonymo s temp file open(U6UW<X'Y>Y'$"$#.r ! open in'memory'file open(WM;'K>out.t+tK $or$die! open o tp t file open(9W7'K>>my.logK $or$die! open file for append open(L<Z'Kc.es.r$<$file$RK ! read from process open(68;</Z;'$KRsort$>;mp$$K ! $rite to process $line$$%$<=>V=96>! "et ne%t line @lines$$%$<=>V=96>! sl rp infile fore.ch$$line$(<:;P=>> A...B loop of lines from :;P=> print$:;P6<<$K[.rning$2."nK! print to :;P6<< close$=>V=96! close filehandle More: binmode'$dbmopen'$dbmclose'$fileno'$flock'$ form.t'$getc'$re.d'$re.ddir'$re.dline'$rewinddir'$ seek'$seekdir'$select'$sysc.ll'$sysreed'$sysseek'$ tell'$telldir'trunc.te'$p.ck'$unp.ck'$#ec

1.2 Arrays and ists

@.$%$(2..? ! $i$%$@.! ($.'$$b $%$($b'$$. ! $+$%$$.425! $i$%$$@.! push(@.'$$s ! $.$%$pop(@. ! chop(@. ! $.$%$shift(@. ! re#erse(@. ! @.$%$sortA$el.$<%>$$elbB(@. ! @.$%$split(/-/'$s ! $s$%$Coin(('$*$@c ! @.D$%$@.42'D'E..-5! @.D$%$grep(F/G@/'$@. !

$.ref$%$"@.! $.ref$%$42'KfooK'undef'2H5! $el$%$$.ref->4)5! $el$%$@A$.refB4)5! $.refD$%$4@A$.ref2B5! $href$%$"1h! $href$%A/L<$%>$,'/M7$%>$3B! array initialization $el$%$$href->A/L<B! n mber of elements in @. $el$%$1A$hrefBA/L<B! s$ap $. and $b $hrefD$%$A1A$href2BB! access to inde% * if$(ref($r $e&$KN/:NK $AB last inde% in @. @.$%$(42'$D5'4H'$,5 ! appends $s to @. $i$%$$.4)5425! removes last element 1No/%(fs%>4KfK'KbK5' remove last char (per el.) $$$$$$sp%>4KhK'KmK5 ! removes first element $n.me$%$$No/AspB425! reverse @. $fh$%$"O:;P=> sort n merically $coderef$%$"Qfnc! split strin" into @. $coderef$%subAprint$Kbl.KB! +oin @. elements into strin" Q$coderef( ! array slice sub$cre.tecntA$my$$c%shift! remove comments from @. $$$$return$sub$A$$ $$$$$$$$print$K$cJJK!$B!$B OfooA;N=>7B

! References and &ata Str'ct'res

reference to array anonymo s array access element of array copy array reference to hash anonymo s hash access element of hash copy hash checks if #r points to hash 2'dim array access 2'dim array hash of arrays access to hash of arrays "lobref code ref (e.". callback) anon s bro tine callin" anon s bro tine clos re& $c$persists foo'synta% for creatin" refs

- Reg'lar .%pressions
($#.r$%~$/re/ '$($#.r$F~$/re/ m/p.ttern/igmso+c &r/p.ttern/imso+ s/p.ttern/repl.cement/igmso+e Modifiers: i o case'insensitive g + "lobal m c m ltiline s e as sin"le line (. matches "n) matches ) does not match matchin" pattern store re"e% in variable search and replace compile once e%tended don.t reset pos ($ith g) eval ate replacement

Synta%: " escape . any sin"le char G start of line $ end of line O'$O\ 0 or more times ("reedy ) non"reedy) J'$J\ * or more times ("reedy ) non"reedy) \'$\\ 0 or * times ("reedy ) non"reedy) "b'$"T $ord bo ndary ( "w ' "[) ) match e%cept at $.b. "/ strin" start ($ith /m "0 strin" end (before "n "z absol te strin" end "7 contin e from previo s m//g 4...5 character set (... "ro p& capt re to $2'$$D (\:... "ro p $itho t capt rin" An'mB$'$An'mB\ at least n times& at most m times An'B$$'$An'B\ at least n times AnB$$$'$AnB\ e%actly n times R or "2'$"D te%t from nth "ro p ($2& ...) .scape Se/'ences: ". "e alarm (beep) escape "f "n formfeed ne$line "r "t carria"e ret rn tab "c+ control'% "l lo$ercase ne%t char "9 "M lo$ercase ntil "6 ppercase ntil "6 "] "6 diable metachars ntil "6 end case modifications C#aracter Classes: 4.my5 .a.& .m.& or .y. 4f-C.-5 ran"e f'+& dot& and dash 4Gf-C5 everythin" e%cept ran"e f'+ "d'$"P di"it 4)--5$/$non-digit "w'$"[ $ord char 4.-z/-0)--^5$/$non-word$ ch.r "s'$": $hitepace 4$"t"n"r"f5$/$non-sp.ce "Z match a byte "pL'$"LL match p'named nicode ) non'p'named' nicode "pA...B'$"LA...B match lon"'named nicode ) non'named' nicode "8 match e%tended nicode Posi%: 4:.lnum5 alphan meric 4:.lph.5 alphabetic 4:.scii:5 any /01II char 4:bl.nk:5 $hitespace 4$"t5 4:cntrl:5 control characters 4:digit:5 di"its 4:gr.ph:5 alphan m 2 p nct ation 4:lower:5 lo$ercase chars 4:print:5 alphan m& p nct& space 4:punct:5 p nct ation 4:sp.ce:5 $hitespace 4"s"ck5 4:upper:5 ppercase chars 4:word:5 alphan m 2 .3. 4:+digit:5 he% di"it 4:Gdigit:5 non'di"it

.%tended Constr'cts (\@te+t (\im+s-ims+:... (\%... '$(\F... (\<%.. '$(\<F.. (\>... (\A$code$B (\\A$code$B (\(cond yesRno (\(cond yes Variables $Q $S $Y $2'$$D$... $J $G> $G< @-'$@J

comment enable or disable option positive ) ne"ative look'ahead positive ) ne"ative look'behind prohibit backtrackin" embedded code dynamic re"e% condition correspondin" to capt red parentheses condition correspondin" to look'aro nd entire matched strin" everythin" prior to matched strin" everythin" after matched strin" n'th capt red e%pression last parenthesis pattern match most recently closed capt. res lt of last (\A...B offsets of starts ) ends of "ro ps

5 ,ne2 iners
-)$ -. -V -i -n -p (zero) specify the inp t record separator split data into an array named 45 specify pattern for 'a to se $hen splittin" edit files in place r n thro "h all the 4/6G7 ar" ments as files& sin" 89 same as 'n& b t $ill also print the contents of #3

)nteracti6e Mode: perl$-de$,D .%amples: *. + st lines *: to *;& efficiently $$$$perl$-ne$Yprint$if$$.$>%$2?!$e+it$if$$.$>%$2b!Y 2. + st lines <=T bet$een line *0 and 20 $$$$perl$-ne$Yprint$unless$2)$..$D)Y -. lines bet$een 0T/6T and ><? $$$$perl$-ne$Yprint$if$/G:;/<;$/$..$/G6>P$/Y @. in'place edit of A.c files chan"in" all foo to bar $$$$perl$-pi.b.k$-e$Ys/"bfoo"b/b.r/gY$O.c :. delete first *0 lines $$$$perl$-i.old$-ne$Yprint$unless$2$..$2)Y$foo.t+t B. chan"e all the isolated oldvar occ rrences to ne$var $$$$perl$-i.old$-pe$YsA"bold#.r"bBAnew#.rBgY$O.4chy5 ;. printin" each line in reverse order $$$$perl$-e$Yprint$re#erse$<>Y$file2$fileD$fileH$.... 8. find palindromes in the ) sr)dict)$ords dictionary file $$$$perl$-lne$Y$^$%$lc$$^!$print$if$$^$e&$re#erseY$ $$$$$$$$/usr/dict/words C. command'line that reverses all the bytes in a file $$$$perl$-)bbbe$Yprint$sc.l.r$re#erse$<>Y$f2$fD$fH *0. $ord $rap bet$een :0 and ;2 chars $$$$perl$-p)))e$Ytr/$"t"n"r/$/! $$$$s/(.A?)'bDB "s/$2"n/g!$^.%K"nK+DY **. strip and remove do ble spaces $$$$perl$-pe$Y$^$%$K$$^$K!$tr/$"t/$/s!$$^$%$ $$$$$$$$substr($^'2'-2 Y *2. move .A.t%t.o t. to .A.o t. $$$$perl$-e$Y($n$%$$^ $%~$s/".t+t(".out $/$2/$.nd$not$ $$$$$$$$-e$$n$.nd$ren.me$$^'$$n$for$@/<7IY$O$

0 ,b1ect2,riented Perl and Mod'les


&efining a ne3 class: $$$$p.ck.ge$Lerson! $$$$use$strict! $$$$sub$new$A$@constructor'$.ny$n.me$is$fine $$$$$$$$my$$cl.ss$%$shift! $$$$$$$$my$$self$$%$AB! $$$$$$$$$self->A>/U6B$%$undef!$@$field $$$$$$$$$self->AK^Z6>:M:KB$%$"$Zensus!$@$cl.ss$d.t. $$$$$$$$JJ$$A$$self->AK^Z6>:M:KB$B! $$$$$$$$bless$($self'$$cl.ss ! $$$$$$$$return$$self! $$$$B $$$$sub$n.me$A$@method $$$$$$$$my$$self$%$shift! $$$$$$$$if$(@^ $A$$self->A>/U6B$%$shift$B $$$$$$$$return$$self->A>/U6B! $$$$B $$$$sub$P6:;<WX$A$@destructor $$$$$$$$my$$self$%$shift!$--$$A$self->AK^Z6>:M:KB$B!B $$$$2!$$@$so$the$_re&uire`$or$_use`$succeeds 4sing t#e class: $$$$use$Lerson! $$$$$him$%$Lerson->new( ! $$$$$him->n.me(Ka.sonK ! $$$$printf$K;hereYs$someone$n.med$1s."nK'$$him->n.me! $$$$use$P.t.::Pumper!$print$Pumper($him !$@$debug

)nstalling Mod'les: perl$-UZL/>$-e$shell!

You might also like