Sei sulla pagina 1di 6

Perl Reference Card Cheat Sheet

by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

About 1.1 Scalars and Strings (cont) 1.2 Arrays and Lists (cont)

This is version 2 of the perl reference card. e(E) scientific notation revers​e(@a); reverse @a
(cl) 2008 Michael Goerz <go​erz​@ph​ysi​k.f​u- f decimal floating point @a = sort{$ela <=> sort numeri​cally
b​erl​in.d​e>.
$elb}(@a);
g, G shorter %e or %f /
http:/​/ww​w.p​hys​ik.f​u-​ber​lin.de​/~g​oerz/
%E or %f @a = split(​/-/​,$s); split string into @a
Inform​ation taken liberally from the perl
docume​ntation and various other sources. o signed octal $s = join(“, ” @c); join @a elements
You may freely distribute this document. into string
s string of chars
@a2 = @a[1,2​,6..9]; array slice
u, x, X unsigned decimal int /
1 Variable Types
hex int / hex int in @a2 = grep(!​/^#/, @a); remove comments
caps from @a
1.1 Scalars and Strings
p address pointer
Perl image
chomp(​$str); discard trailing \n n nothing printed
$v = chop($​str); $v becomes trailing modifiers: h,l,L arg is short int / long
char int, double/ long

eq, ne, lt, gt, le, ge, string comparison double

cmp More:

$str = “0” x 4; $str is now “0000” chr, crypt, hex, lc, q/STRING/,
$v = index(​$str, $x); find index of $x in $str, lcfirst, length, oct, ord, qq/STR​ING/, reverse,
pack uc, ucfirst
$v = rindex​($str, $x); starting from left or right

$v = substr​($str, extract substring 1.2 Arrays and Lists


$strt, $len);
@a = (1..5); array initia​liz​ation
$cnt = $sky =~ tr/0- count the digits in $sky
9//; $i = @a; number of elements in
@a
$str =~ tr/a-zA-Z/ change non-alphas to
/cs; space ($a, $b) = ($b, swap $a and $b
1.3 Hashes
$a);
$v = sprint​f(“%10s format string
%08d”,​$s,$n); $x = $a[1]; access to index 1 %h=(k1 => “val1”,k2 hash initia​liz​ation
=> 3);
Format String: %[flag​s][​0] $i = $#a; last index in @a
[​wid​th]​[.p​rec​isi​on]​[mo​d]ty $val = $map{k1}; recall value
push(@a, $s); appends $s to @a
pe @a = %h; array of keys and
$a = pop(@a); removes last element
types: values
chop(@a); remove last char (per el.)
%h = @a; create hash from array
c character
$a = shift(@a); removes first element
foreach $k iterate over list of keys
d(i) signed decimal int
(keys(​%h)​){..}

foreach $v iterate over list of


(vals(​%h)​){..} values

while (($k,$​v)=each iterate over key-


%h){..} va​lue​-pairs

delete $h{k1}; delete key

exists $h{k1} does key exist?

defined $h{k1} is key defined?

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 1 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

3 References and Data Structures 3 References and Data Structures (cont) 2 Basic Syntax (cont)

$aref = \@a; reference to sub createcnt{ my $c=shift; closure, $c eval {$a=$a/$b; }; warn $@ exception
array return sub { print "​$c+​+"; }; } persists if $@; handling

$aref = [1,"​foo​"​,un​def​,13]; anonymous array *foo{T​HING} foo-syntax for


creating refs 6 Regular Expres​sions
$el = $aref-​>[0]; $el = access element
@{$are​f}[0]; of array ($var =~ /re/), matches / does not match
Link to perl cheat ($var !~ /re/)
$aref2 = [@{$ar​ef1}]; copy array

$href = \%h; reference to perlcheat m/patt​ern​/ig​msox matching pattern

hash http:/​/ww​w.c​hea​tog​rap​hy.c​om​/mi​shi​n/c​hea​t- c

$href ={APR => 4,AUG => anonymous hash s​hee​ts/​per​lcheat/ qr/pat​ter​n/imsox store regex in variable

8}; perl-r​efe​ren​ce-card s/patt​ern​/re​pla​ce search and replace

$el = $href-​>{APR}; $el = access element m​ent​/ig​msoxe


http:/​/ww​w.c​hea​tog​rap​hy.c​om​/mi​shi​n/c​hea​t-
%{$hre​f}{​APR}; of hash s​hee​ts/​per​l-r​efe​ren​ce-​card/ Modi​fie​rs:

$href2 = {%{$hr​ef1}}; copy hash i case- o compile once


20-kil​ler​-pe​rl-​pro​gra​mmi​ng-tips
if (ref($r) eq "​HAS​H") {} checks if $r i​nse​nsitive
http:/​/ww​w.c​hea​tog​rap​hy.c​om​/mi​shi​n/c​hea​t-
points to hash g global x extended
s​hee​ts/​20-​kil​ler​-pe​rl-​pro​gra​mmi​ng-​tip​s-
@a = ([1, 2],[3, 4]); 2-dim array f​or-​beg​inners/ s as single line (. e evaluate replac​ement
$i = $a[0][1]; access 2-dim matches \n)
array 2 Basic Syntax Synt​ax:
%HoA=(​fs=​>["f​"​,"b"], sp=> hash of arrays ($a, $b) = read command line \ escape
["h​"​,"m"]); shift(​@ARGV); params . any single char
$name = $HoA{s​p}[1]; access to hash sub p{my $var = define subroutine ^ start of line
of arrays shift; ...}
$ end of line
$fh = *STDIN globref p(“bla”); execute subroutine
,? 0 or more times (greedy /
$coderef = \&fnc; code ref (e.g.
if(expr){} elsif {} condit​ional nongreedy)
callback)
else {}
+, +? 1 or more times (greedy /
$coderef =sub{print "​bla​"}; anon subroutine unless (expr){} negative condit​ional nongreedy)
&$​cod​eref(); calling anon while (expr){} while-loop ?, ?? 0 or 1 times (greedy /
subroutine
until (expr){} until-loop nongreedy)

do {} until (expr) postcheck until-loop \b, \B word boundary ( \w - \W) /


match except at w.b.
for($i=1; $i<=10; for-loop
$i++){} \A string start (with /m)

foreach $i (@list){} foreac​h-loop \Z string end (before \n)

last, next, redo end loop, skip to next, \z absolute string end
jump to top

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 2 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

6 Regular Expres​sions (cont) 6 Regular Expres​sions (cont) 6 Regular Expres​sions (cont)

\G continue from previous \w, \W word char [a-zA-​Z0-9_] / non-word (?<​=..), (? positive / negative look-b​ehind
m//g char <!..)

[...] character set \s, \S whitepace [ \t\n\r\f] / non-space (?>...) prohibit backtr​acking

(...) group, capture to $1, $2 \C match a byte (?{ code embedded code

(?:...) group without capturing \pP, \PP match p-named unicode / non- })

p-​nam​ed-​unicode (??{ code dynamic regex


{n,m} , {n,m}? at least n times, at most
})
m times \p{...}, match long-named unicode / non-

{n,} , {n,}? at least n times \P{...} na​med​-un​icode (? condition corres​ponding to

\X match extended unicode (con​d)y​es| captured parent​heses


{n} , {n}? exactly n times
no)
Posix:
| or
(? condition corres​ponding to look-
\1, \2 text from nth group ($1, [:alnum:] alphan​umeric
(con​d)yes) a​round
...) [:alpha:] alphabetic Vari​ables
Escape Sequen​ces: [:ascii:] any ASCII char
$& entire matched string
\a alarm (beep) \e escape [:blank:] whitespace [ \t]
$` everything prior to matched string
\f formfeed \n newline [:cntrl:] control characters
$' everything after matched string
\r carriage return \t tab [:digit:] digits
$1, $2 ... n-th captured expression
\cx control-x \l lowercase next char [:graph:] alphanum + punctu​ation
$+ last parent​hesis pattern match
\L lowercase until \E \U uppercase until \E [:lower:] lowercase chars
$^N most recently closed capt.
\Q diable metachars \E end case [:print:] alphanum, punct, space
$^R result of last (?{...})
until \E modifi​cations [:punct:] punctu​ation
@-, @+ offsets of starts / ends of groups
Char​acter Classes: [:space:] whitespace [\s\ck]
http:/​/pe​rld​oc.p​er​l.o​rg/​per​lre​qui​ck.html
[amy] 'a', 'm', or 'y' [:upper:] uppercase chars
http:/​/ha​bra​hab​r.r​u/p​ost​/17126/
[f-j.-] range f-j, dot, and dash [:word:] alphanum + '_'
[^f-j] everything except range [:xdigit:] hex digit
f-j
[:^digit:] non-digit
\d, \D digit [0-9] / non-digit
Extended Constr​ucts

(?#text) comment

(?imxs​- enable or disable option


im​sx:...)

(?=...), positive / negative look-ahead


(?!...)

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 3 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

Debugging regexp 4 System Intera​ction (cont) 5 Input/​Output (cont)

use re 'taint'; File Tests: open(P​RC,​"​caesar <$file read from


# Contents of $match are tainted if $dirty was |"); process
-r, -w readable, writeable
also tainted.
open(E​XTRACT, "​|sort write to process
-x executable
($match) = ($dirty =~ /^(.*)​$/s);
>Tm​p$$​");
# Allow code interp​ola​tion: -e exists
$line = <IN​FIL​E>; get next line
use re 'eval';
-f, -d, -l is file, directory,
$pat = '(?{ $var = 1 })'; # embedded code @lines = <IN​FIL​E>; slurp infile
symlink
execution foreach $line loop of lines from
-T, -B text file, binary file
/alpha​${p​at}​omega/; # won't fail unless under -T (<S​TDI​N>)​{...} STDIN
# and $pat is tainted -M, -A mod/access age in
print STDERR "​Warning print to STDERR
use re 'debug'; # like "perl -Dr" days
1.\n";
/^(.*)$/s; # output debugging info during @stats = 13-element list with
# compile time and run time close INFILE; close filehandle
stat(“​fil​ena​me”); status
use re 'debug​color'; # same as 'debug', More:
File Tests in Perl http:/​/ww​w.d​evs​hed.co​
# but with colored output
m/c​/a/​Per​l/F​ile​-Te​sts​- binmode, dbmopen, select, syscall,
in​-Perl/ dbmclose, fileno, flock, sysreed, sysseek,
4 System Intera​ction
format, getc, read, readdir, tell,
More:
system​(“cat $f|sort - system call readline, rewinddir, seek, telldi​r,t​run​cate,
chmod, chown, opendir, readlink,
u>​$f.s”); seekdir pack, unpack,
chroot, fcntl, glob, rename, rmdir,
vec
@a = readpi​pe(​“ls​mod”); catch output ioctl, link, lstat, mkdir, symlink, umask, utime
$today = “Today: “.date; catch output
7 Object​-Or​iented Perl and Modules
5 Input/​Output
better: use IPC::Open3 'open3';!
Defining a new class:
chroot​(“/​hom​e/u​ser/”); change root open(I​NFI​LE,​"​in.t​xt​") or open file for input
package Person;
die;
while (<*.c>) {} operate on all c- use strict;
files open(I​NFI​LE,​"​<:u​tf8​"​,"fi​l open file with my $Census;
e"); encoding sub new { #const​ructor, any name is fine
unlink​(“/​tmp​/fi​le”); delete file
open(TMP, "​+>", open anonymous my $class = shift;
if (-f “file.t​xt​”){...} file test my $self = {};
undef); temp file
$self-​>{NAME} = undef; # field
open(M​EMO​RY,​'>', open in-mem​ory​-file
$self-​>{"_​CEN​SUS​"} = \$Census; # class data
\$var);
++ ${ $self-​>{"_​CEN​SUS​"} };
open(O​UT,​"​>ou​t.t​xt") or open output file bless ($self, $class);
die; return $self;
open(L​OG,​"​>>m​y.l​og") open file for append }
or die; sub name { #method
my $self = shift;

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 4 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

7 Object​-Or​iented Perl and Modules (cont) 8 One-Liners (cont) 8 One-Liners (cont)

if (@_) { $self-​>{NAME} = shift } -p same as -n, but will also print the -l enables automatic line-e​nding
return $self-​>{N​AME}; contents of $_ processing in the output. Print
} statements will have the new line
Intera​ctive perl -de1;use Term::​Rea​dKey;
sub DESTROY { #destr​uctor separator (\n) added at the end of
Mode:
my $self = shift; -- ${$sel​f->​{"_C​ENS​US"} };} each line.
http:/​/sz​abg​ab.c​om​/us​ing​-th​e-
1; # so the ‘require’ or ‘use’ succeeds
b​uil​t-i​n-d​ebu​gge​r-o​f-p​erl​-as​- -w prints any warning messages.
Using the class:
re​pl.html -e indicates that the following string
use Person;
is to be interp​reted as a perl
$him = Person​->n​ew(); perl- http:/​/ww​w.t​heg​eek​stu​ff.c​om​/20​10/​05
script (i.e., sequence of
$him->​nam​e("J​aso​n"); d​ebugger /​per​l-d​ebu​gger/
commands).
printf "​There's someone named %s.\n", $him- The Perl http:/​/do​cst​ore.mi​k.u​a/o​rel​ly/​per​l/p​ro
>​name; Debugger g​3/c​h20​_01.htm http:/​/pe​rld​oc.p​er​l.o​rg/​per​lru​n.html
use Data::​Dumper; print Dumper​($him); # Perl flags - perl -e '$x = "​Hello world!​n"; print
-T enables taint checking, which
debug pe, -pi, -p, $x;'
instructs perl to keep track of data
http:/​/ww​w.c​ode​pro​jec​t.c​om/​Art​icl​es/​315​2/P​erl​- -w, -d, -i, -
from the user and avoid doing
Ob​jec​t-O​rie​nte​d-P​rog​ramming t? perldoc
anything insecure with it. Here this
http:/​/yn​onp​ere​k.c​om/​cou​rse​/pe​rl/​oo.html perlrun
option is used to avoid taking the
current directory name from the perl -MO=De​parse -p -e 1
Installing Modules:
@INC variable and listing the
perl -MO=De​parse -p -i -e 1
perl -MCPAN -e shell; available .pm files from the
perl -MO=De​parse -p -i.bak -e 1
directory recurs​ively.
https:​//t​wit​ter.co​m/#​!/p​erl​one​liner
8 One-Liners

- (zero) specify the input record separator Examples:


0
1. just lines 15 to 17, effici​ently
- split data into an array named @F
a perl -ne 'print if $. >= 15; exit if $. >= 17;'

- specify pattern for -a to use when splitting 2. just lines NOT between line 10 and 20
F perl -ne 'print unless 10 .. 20'
-i edit files in place

- run through all the @ARGV arguments as


n files, using <>

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 5 of 6. http://crosswordcheats.com
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/

Examples: (cont) Examples: (cont)

3. lines between START and END 14. If you had installed any modules from
CPAN, then you will need to re-install all of
perl -ne 'print if /START$/ .. / END$/'
them. (Naveed Massjouni)
4. in-place edit of *.c files changing all foo to
perl -E 'say for grep /site_​per​l/,​@INC'| xargs
bar
find | perl -Fsite​_perl/ -lane 'print $F[1] if
perl -pi.bak -e 's/\bf​oo​\b/b​ar/g' *.c /\.pm$/' | cpanm --rein​stall

5. delete first 10 lines 15. Give executable rights to all perl file in dir
perl -i.old -ne 'print unless 1 .. 10' foo.txt find /home/​cli​ent​0/p​ubl​ic_html -type f -name
'*.pl' -print0 | xargs -0 chmod 0755
6. change all the isolated oldvar occurr​ences to
newvar 16. Find files matching name-p​attern
perl -i.old -pe 's{\bo​ldv​ar​\b}{​new​var}g' *.[chy] https:​//g​ist.gi​thu​b.c​om/​563679

perl -MFile​::Find -le 'find(​sub​{print


7. printing each line in reverse order
$File:​:Fi​nd:​:name if /\b[a-​z]{​2}_​[A-​Z]
perl -e 'print reverse <>' file1 file2 file3 ....
{​2}/​},"/​usr​")'
8. find palind​romes in the /usr/d​ict​/words
dictionary file

perl -lne '$_ = lc $_; print if $_ eq reverse'


/usr/d​ict​/words

9. comman​d-line that reverses all the bytes in a


file

perl -0777e 'print scalar reverse <>' f1 f2 f3

10. word wrap between 50 and 72 chars

perl -p000e 'tr/ \t\n\r/ /; s/(.


{5​0,7​2})​\s/​$1​\n/g​;$_.="​\n"x2'

11. strip and remove double spaces

perl -pe '$_ = " $_ "; tr/ \t/ /s; $_ =


substr​($_​,1,-1)'

12. move '.txt.out' to '.out'

perl -e '($n = $_) =~ s/\.tx​t(\.ou​t)$/$1/ and


not -e $n and rename $_, $n for @ARGV' *

13. write a hash slice, which we have come as


a reference to a hash

perl -E'my $h={1..8}; say for @{$h}{​1,3​,5,7}'

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by CrosswordCheats.com


cheatography.com/mishin/ Last updated 5th June, 2014. Learn to solve cryptic crosswords!
mishin.narod.ru Page 6 of 6. http://crosswordcheats.com

Potrebbero piacerti anche