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 docmentation and varios other sorces.
!o may freely distribte this docment.
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' $+!
$# % rinde+($str' $+!
find inde% of $+ in $str&
startin" from left or ri"ht
$# % substr($str' $strt' $len! e%tract sbstrin"
$cnt % $sky %~ tr/)--//! cont 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& doble) lon" doble
More: chr' crypt' he+' lc' lcfirst' length' oct' ord'
p.ck' &/:;<=>7/' &&/:;<=>7/' re#erse' uc' ucfirst
1.2 Arrays and ists
@. % (2..?! array initialization
$i % @.! nmber of elements in @.
($.' $b % ($b' $.! s$ap $. and $b
$+ % $.425! access to inde% *
$i % $@.! last inde% in @.
push(@.' $s! appends $s to @.
$. % pop(@.! removes last element
chop(@.! remove last char (per el.)
$. % shift(@.! removes first element
re#erse(@.! reverse @.
@. % sortA$el. <%> $elbB(@.! sort nmerically
@. % split(/-/'$s! split strin" into @.
$s % Coin((' * @c! +oin @. elements into strin"
@.D % @.42'D'E..-5! array slice
@.D % grep(F/G@/' @.! remove comments from @.
1.! "as#es
1h%(k2 %> (#.l2*'kD %> H! hash initialization
$#.l % $m.pAk2B! recall vale
@. % 1h! array of keys and vales
1h % @.! create hash from array
fore.ch $k (keys(1hA..B iterate over list of keys
fore.ch $# (#.ls(1hA..B iterate over list of vales
while (($k'$#%e.ch 1hA..B iterate over key'vale'pairs
delete $hAk2B! delete key
e+ists $hAk2B does key e%ist,
defined $hAk2B is key defined,
2 $asic Synta%
($.' $b % shift(@/<7I! read command line params
sub pAmy $#.r % shift! ...B define sbrotine
p((bl.*! e%ecte sbrotine
if(e+prAB elsif AB else AB conditional
unless (e+prAB ne"ative conditional
while (e+prAB $hile'loop
until (e+prAB ntil'loop
do AB until (e+pr postcheck ntil'loop
for($i%2! $i<%2)! $iJJAB for'loop
fore.ch $i (@listAB foreach'loop
l.st' ne+t' redo end loop& skip to ne%t& +mp to top
e#.l A$.%$./$b! B!
w.rn $@ if $@!
e%ception handlin"
! References and &ata Str'ct'res
$.ref % "@.! reference to array
$.ref % 42'KfooK'undef'2H5! anonymos array
$el % $.ref->4)5!
$el % @A$.refB4)5!
access element of array
$.refD % 4@A$.ref2B5! copy array
$href % "1h! reference to hash
$href %A/L< %> ,'/M7 %> 3B! anonymos hash
$el % $href->A/L<B!
$el % 1A$hrefBA/L<B!
access element of hash
$hrefD % A1A$href2BB! copy hash
if (ref($r e& KN/:NK AB checks if #r points to hash
@. % (42' D5'4H' ,5! 2'dim array
$i % $.4)5425! access 2'dim array
1No/%(fs%>4KfK'KbK5'
sp%>4KhK'KmK5!
hash of arrays
$n.me % $No/AspB425! access to hash of arrays
$fh % "O:;P=> "lobref
$coderef % "Qfnc! code ref (e.". callback)
$coderef %subAprint Kbl.KB! anon sbrotine
Q$coderef(! callin" anon sbrotine
sub cre.tecntA my $c%shift!
return sub A
print K$cJJK! B! B
closre& $c persists
OfooA;N=>7B foo'synta% for creatin" refs
( System )nteraction
system((c.t $fRsort -u>$f.s*! system call
@. % re.dpipe((lsmod*! catch otpt
$tod.y % (;od.y: (.Sd.teS! catch otpt
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%ectable
-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 stats
More: chmod' chown' chroot' fcntl' glob' ioctl' link'
lst.t' mkdir' opendir' re.dlink' ren.me' rmdir'
symlink' um.sk' utime
* )np't+,'tp't
open(=>V=96'Kin.t+tK or die! open file for inpt
open(=>V=96'K<:utf3K'KfileK! open file $ith encodin"
open(;UL' KJ>K' undef! open anonymos temp file
open(U6UW<X'Y>Y' "$#.r! open in'memory'file
open(WM;'K>out.t+tK or die! open otpt 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>! slrp 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
- Reg'lar .%pressions
($#.r %~ /re/' ($#.r F~ /re/ matches ) does not match
m/p.ttern/igmso+c matchin" pattern
&r/p.ttern/imso+ store re"e% in variable
s/p.ttern/repl.cement/igmso+e search and replace
Modifiers:
i case'insensitive o compile once
g "lobal + e%tended
m mltiline c don.t reset pos ($ith g)
s as sin"le line (. matches "n) e evalate 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 bondary ( "w ' "[) ) match e%cept at $.b.
"/ strin" start ($ith /m
"0 strin" end (before "n
"z absolte strin" end
"7 contine from previos m//g
4...5 character set
(... "rop& captre to $2' $D
(\:... "rop $ithot captrin"
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 "rop ($2& ...)
.scape Se/'ences:
". alarm (beep) "e escape
"f formfeed "n ne$line
"r carria"e retrn "t tab
"c+ control'% "l lo$ercase ne%t char
"9 lo$ercase ntil "6 "M ppercase ntil "6
"] diable metachars ntil "6 "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 alphanmeric
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 alphanm 2 pnctation
4:lower:5 lo$ercase chars
4:print:5 alphanm& pnct& space
4:punct:5 pnctation
4:sp.ce:5 $hitespace 4"s"ck5
4:upper:5 ppercase chars
4:word:5 alphanm 2 .3.
4:+digit:5 he% di"it
4:Gdigit:5 non'di"it
.%tended Constr'cts
(\@te+t comment
(\im+s-ims+:... enable or disable option
(\%...' (\F... positive ) ne"ative look'ahead
(\<%..' (\<F.. positive ) ne"ative look'behind
(\>... prohibit backtrackin"
(\A code B embedded code
(\\A code B dynamic re"e%
(\(condyesRno condition correspondin" to captred parentheses
(\(condyes condition correspondin" to look'arond
Variables
$Q entire matched strin"
$S everythin" prior to matched strin"
$Y everythin" after matched strin"
$2' $D ... n'th captred e%pression
$J last parenthesis pattern match
$G> most recently closed capt.
$G< reslt of last (\A...B
@-' @J offsets of starts ) ends of "rops
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!
5 ,ne2iners
-) (zero) specify the inpt record separator
-. split data into an array named 45
-V specify pattern for 'a to se $hen splittin"
-i edit files in place
-n rn thro"h all the 4/6G7 ar"ments as files& sin" 89
-p same as 'n& bt $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 occrrences 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 doble spaces
perl -pe Y$^ % K $^ K! tr/ "t/ /s! $^ %
substr($^'2'-2Y
*2. move .A.t%t.ot. to .A.ot.
perl -e Y($n % $^ %~ s/".t+t(".out$/$2/ .nd not
-e $n .nd ren.me $^' $n for @/<7IY O

You might also like