About

(cl) 2008 Michael Goerz <go­erz­@ph­ysi­k.f­u-b­erl­in.d­e>.

http:/­/ww­w.p­hys­ik.f­u-­ber­lin.de­/~g­oerz/

Inform­ation taken liberally from the perl docume­ntation and various other sources.

You may freely distribute this document. This is version 2 of the perl reference card.(cl) 2008 Michael Goerz .Inform­ation taken liberally from the perl docume­ntation and various other sources.You may freely distribute this document. 1 Variable Types 1.1 Scalars and Strings chomp(­$str); discard trailing

$v = chop($­str); $v becomes trailing char eq, ne, lt, gt, le, ge, cmp string comparison $str = “0” x 4; $str is now “0000” $v = index(­$str, $x); find index of $x in $str, $v = rindex­($str, $x); starting from left or right $v = substr­($str, $strt, $len); extract substring $cnt = $sky =~ tr/0-9//; count the digits in $sky $str =~ tr/a-zA-Z/ /cs; change non-alphas to space $v = sprint­f(“%10s %08d”,­$s,$n); format string Format String: %[flag­s][­0][­wid­th]­[.p­rec­isi­on]­[mo­d]type types: c character d(i) signed decimal int e(E) scientific notation f decimal floating point g, G shorter %e or %f / %E or %f o signed octal s string of chars u, x, X unsigned decimal int / hex int / hex int in caps p address pointer n nothing printed modifiers: h,l,L arg is short int / long int, double/ long double More: chr, crypt, hex, lc, lcfirst, length, oct, ord, pack q/STRING/, qq/STR­ING/, reverse, uc, ucfirst 1.2 Arrays and Lists @a = (1..5); array initia­liz­ation $i = @a; number of elements in @a ($a, $b) = ($b, $a); swap $a and $b $x = $a[1]; access to index 1 $i = $#a; last index in @a push(@a, $s); appends $s to @a $a = pop(@a); removes last element chop(@a); remove last char (per el.) $a = shift(@a); removes first element revers­e(@a); reverse @a @a = sort{$ela <=> $elb}(@a); sort numeri­cally @a = split(­/-/­,$s); split string into @a $s = join(“, ” @c); join @a elements into string @a2 = @a[1,2­,6..9]; array slice @a2 = grep(!­/^#/, @a); remove comments from @a Perl image 1.3 Hashes %h=(k1 => “val1”,k2 => 3); hash initia­liz­ation $val = $map{k1}; recall value @a = %h; array of keys and values %h = @a; create hash from array foreach $k (keys(­%h)­){..} iterate over list of keys foreach $v (vals(­%h)­){..} iterate over list of values while (($k,$­v)=each %h){..} iterate over key-va­lue­-pairs delete $h{k1}; delete key exists $h{k1} does key exist? defined $h{k1} is key defined? 3 References and Data Structures $aref = \@a; reference to array $aref = [1,"­foo­"­,un­def­,13]; anonymous array $el = $aref-­>[0]; $el = @{$are­f}[0]; access element of array $aref2 = [@{$ar­ef1}]; copy array $href = \%h; reference to hash $href ={APR => 4,AUG => 8}; anonymous hash $el = $href-­>{APR}; $el = %{$hre­f}{­APR}; access element of hash $href2 = {%{$hr­ef1}}; copy hash if (ref($r) eq "­HAS­H") {} checks if $r points to hash @a = ([1, 2],[3, 4]); 2-dim array $i = $a[0][1]; access 2-dim array %HoA=(­fs=­>["f­"­,"b"], sp=>["h­"­,"m"]); hash of arrays $name = $HoA{s­p}[1]; access to hash of arrays $fh = *STDIN globref $coderef = \&fnc; code ref (e.g. callback) $coderef =sub{print "­bla­"}; anon subroutine &$­cod­eref(); calling anon subroutine sub createcnt{ my $c=shift; return sub { print "­$c+­+"; }; } closure, $c persists *foo{T­HING} foo-syntax for creating refs Link to perl cheat perlcheat http:/­/ww­w.c­hea­tog­rap­hy.c­om­/mi­shi­n/c­hea­t-s­hee­ts/­per­lcheat/ perl-r­efe­ren­ce-card http:/­/ww­w.c­hea­tog­rap­hy.c­om­/mi­shi­n/c­hea­t-s­hee­ts/­per­l-r­efe­ren­ce-­card/ 20-kil­ler­-pe­rl-­pro­gra­mmi­ng-tips http:/­/ww­w.c­hea­tog­rap­hy.c­om­/mi­shi­n/c­hea­t-s­hee­ts/­20-­kil­ler­-pe­rl-­pro­gra­mmi­ng-­tip­s-f­or-­beg­inners/ 2 Basic Syntax ($a, $b) = shift(­@ARGV); read command line params sub p{my $var = shift; ...} define subroutine p(“bla”); execute subroutine if(expr){} elsif {} else {} condit­ional unless (expr){} negative condit­ional while (expr){} while-loop until (expr){} until-loop do {} until (expr) postcheck until-loop for($i=1; $i<=10; $i++){} for-loop foreach $i (@list){} foreac­h-loop last, next, redo end loop, skip to next, jump to top eval {$a=$a/$b; }; warn $@ if $@; exception handling

6 Regular Expres­sions ($var =~ /re/), ($var !~ /re/) matches / does not match m/patt­ern­/ig­msoxc matching pattern qr/pat­ter­n/imsox store regex in variable s/patt­ern­/re­pla­cem­ent­/ig­msoxe search and replace Modi­fie­rs: i case-i­nse­nsitive o compile once g global x extended s as single line (. matches

) e evaluate replac­ement Synt­ax: \ escape . any single char ^ start of line $ end of line , ? 0 or more times (greedy / nongreedy) +, +? 1 or more times (greedy / nongreedy) ?, ?? 0 or 1 times (greedy / nongreedy) \b, \B word boundary ( \w - \W) / match except at w.b. \A string start (with /m) \Z string end (before

) \z absolute string end \G continue from previous m//g [...] character set (...) group, capture to $1, $2 (?:...) group without capturing {n,m} , {n,m}? at least n times, at most m times {n,} , {n,}? at least n times {n} , {n}? exactly n times | or \1, \2 text from nth group ($1, ...) Escape Sequen­ces: \a alarm (beep) \e escape \f formfeed

newline \r carriage return \t tab \cx control-x \l lowercase next char \L lowercase until \E \U uppercase until \E \Q diable metachars until \E \E end case modifi­cations Char­acter Classes: [amy] 'a', 'm', or 'y' [f-j.-] range f-j, dot, and dash [^f-j] everything except range f-j \d, \D digit [0-9] / non-digit \w, \W word char [a-zA-­Z0-9_] / non-word char \s, \S whitepace [ \t

\r\f] / non-space \C match a byte \pP, \PP match p-named unicode / non-p-­nam­ed-­unicode \p{...}, \P{...} match long-named unicode / non-na­med­-un­icode \X match extended unicode Posix: [:alnum:] alphan­umeric [:alpha:] alphabetic [:ascii:] any ASCII char [:blank:] whitespace [ \t] [:cntrl:] control characters [:digit:] digits [:graph:] alphanum + punctu­ation [:lower:] lowercase chars [:print:] alphanum, punct, space [:punct:] punctu­ation [:space:] whitespace [\s\ck] [:upper:] uppercase chars [:word:] alphanum + '_' [:xdigit:] hex digit [:^digit:] non-digit Extended Constr­ucts (?#text) comment (?imxs­-im­sx:...) enable or disable option (?=...), (?!...) positive / negative look-ahead (?<­=..), (?<!..) positive / negative look-b­ehind (?>...) prohibit backtr­acking (?{ code }) embedded code (??{ code }) dynamic regex (?(con­d)y­es|no) condition corres­ponding to captured parent­heses (?(con­d)yes) condition corres­ponding to look-a­round Vari­ables $& entire matched string $` everything prior to matched string $' everything after matched string $1, $2 ... n-th captured expression $+ last parent­hesis pattern match $^N most recently closed capt. $^R result of last (?{...}) @-, @+ offsets of starts / ends of groups http:/­/pe­rld­oc.p­er­l.o­rg/­per­lre­qui­ck.html http:/­/ha­bra­hab­r.r­u/p­ost­/17126/ Debugging regexp use re 'taint';

# Contents of $match are tainted if $dirty was also tainted.

($match) = ($dirty =~ /^(.*)­$/s);



# Allow code interp­ola­tion:

use re 'eval';

$pat = '(?{ $var = 1 })'; # embedded code execution

/alpha­${p­at}­omega/; # won't fail unless under -T

# and $pat is tainted



use re 'debug'; # like "perl -Dr"

/^(.*)$/s; # output debugging info during

# compile time and run time



use re 'debug­color'; # same as 'debug',

# but with colored output 4 System Intera­ction system­(“cat $f|sort -u>­$f.s”); system call @a = readpi­pe(­“ls­mod”); catch output $today = “Today: “. date ; catch output better: use IPC::Open3 'open3';! chroot­(“/­hom­e/u­ser/”); change root while (<*.c>) {} operate on all c-files unlink­(“/­tmp­/fi­le”); delete file if (-f “file.t­xt­”){...} file test File Tests: -r, -w readable, writeable -x executable -e exists -f, -d, -l is file, directory, symlink -T, -B text file, binary file -M, -A mod/access age in days @stats = stat(“­fil­ena­me”); 13-element list with status File Tests in Perl http:/­/ww­w.d­evs­hed.co­m/c­/a/­Per­l/F­ile­-Te­sts­-in­-Perl/ More: chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, opendir, readlink, rename, rmdir, symlink, umask, utime