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
reverse(@a);
reverse @a
(cl) 2008 Michael Goerz <goerz@physik.fu-
decimal floating point
@a = sort{$ela <=>
sort numerically
berlin.de>.
http://www.physik.fu-berlin.de/~goerz/
g, G
shorter %e or %f /
Information taken liberally from the perl
$elb}(@a);
%E or %f
@a = split(/-/,$s);
split string into @a
$s = join(, @c);
join @a elements
documentation and various other sources.
signed octal
You may freely distribute this document.
string of chars
u, x, X
unsigned decimal int /
@a2 = @a[1,2,6..9];
array slice
hex int / hex int in
@a2 = grep(!/^#/, @a);
remove comments
1 Variable Types
into string
caps
1.1 Scalars and Strings
address pointer
chomp($str);
discard trailing \n
nothing printed
$v = chop($str);
$v becomes trailing
modifiers: h,l,L
arg is short int / long
eq, ne, lt, gt, le, ge,
char
int, double/ long
string comparison
double
cmp
Perl image
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/STRING/, reverse,
$v = rindex($str, $x);
starting from left or right
pack
uc, ucfirst
$v = substr($str,
extract substring
$strt, $len);
$cnt = $sky =~ tr/0-
count the digits in $sky
9//;
$str =~ tr/a-zA-Z/
change non-alphas to
/cs;
space
$v = sprintf(%10s
format string
1.2 Arrays and Lists
@a = (1..5);
array initialization
$i = @a;
number of elements in
@a
($a, $b) = ($b,
swap $a and $b
$a);
$x = $a[1];
access to index 1
%[flags][0]
$i = $#a;
last index in @a
[width][.precision][mod]ty
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
%08d,$s,$n);
Format String:
from @a
pe
types:
c
character
d(i)
signed decimal int
1.3 Hashes
%h=(k1 => val1,k2
hash initialization
=> 3);
$val = $map{k1};
recall value
@a = %h;
array of keys and
values
%h = @a;
create hash from array
foreach $k
iterate over list of keys
(keys(%h)){..}
foreach $v
iterate over list of
(vals(%h)){..}
values
while (($k,$v)=each
iterate over key-
%h){..}
value-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",undef,13];
anonymous array
*foo{THING}
foo-syntax for
$el = $aref->[0]; $el =
access element
@{$aref}[0];
of array
$aref2 = [@{$aref1}];
copy array
$href = \%h;
reference to
$href ={APR => 4,AUG =>
($var =~ /re/),
Link to perl cheat
perlcheat
m/pattern/igmsox
anonymous hash
sheets/perlcheat/
qr/pattern/imsox
store regex in variable
perl-reference-card
s/pattern/replace
search and replace
access element
of hash
$href2 = {%{$href1}};
copy hash
if (ref($r) eq "HASH") {}
checks if $r
points to hash
2-dim array
http://www.cheatography.com/mishin/cheatsheets/perl-reference-card/
20-killer-perl-programming-tips
http://www.cheatography.com/mishin/cheat-
ment/igmsoxe
Modifiers:
i case-
o compile once
insensitive
sheets/20-killer-perl-programming-tips-
g global
x extended
for-beginners/
s as single line (.
e evaluate replacement
matches \n)
access 2-dim
array
2 Basic Syntax
hash of arrays
($a, $b) =
read command line
escape
shift(@ARGV);
params
any single char
sub p{my $var =
define subroutine
start of line
end of line
,?
0 or more times (greedy /
["h","m"]);
$name = $HoA{sp}[1];
matching pattern
http://www.cheatography.com/mishin/cheat-
%{$href}{APR};
%HoA=(fs=>["f","b"], sp=>
matches / does not match
($var !~ /re/)
hash
$el = $href->{APR}; $el =
$i = $a[0][1];
6 Regular Expressions
8};
@a = ([1, 2],[3, 4]);
creating refs
access to hash
of arrays
$fh = *STDIN
globref
$coderef = \&fnc;
code ref (e.g.
callback)
Syntax:
shift; ...}
p(bla);
execute subroutine
if(expr){} elsif {}
conditional
else {}
$coderef =sub{print "bla"};
anon subroutine
unless (expr){}
negative conditional
&$coderef();
calling anon
while (expr){}
while-loop
until (expr){}
until-loop
do {} until (expr)
postcheck until-loop
for($i=1; $i<=10;
for-loop
subroutine
$i++){}
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)
foreach $i (@list){}
foreach-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 Expressions (cont)
6 Regular Expressions (cont)
6 Regular Expressions (cont)
\G
\w, \W
word char [a-zA-Z0-9_] / non-word
(?<=..), (?
char
<!..)
continue from previous
m//g
positive / negative look-behind
[...]
character set
\s, \S
whitepace [ \t\n\r\f] / non-space
(?>...)
prohibit backtracking
(...)
group, capture to $1, $2
\C
match a byte
(?{ code
embedded code
(?:...)
group without capturing
\pP, \PP
match p-named unicode / non-
})
{n,m} , {n,m}?
at least n times, at most
p-named-unicode
(??{ code
dynamic regex
})
m times
\p{...},
match long-named unicode / non-
{n,} , {n,}?
at least n times
\P{...}
named-unicode
(?
condition corresponding to
{n} , {n}?
exactly n times
\X
match extended unicode
(cond)yes|
captured parentheses
or
Posix:
\1, \2
text from nth group ($1,
[:alnum:]
alphanumeric
...)
[:alpha:]
alphabetic
[:ascii:]
any ASCII char
Escape Sequences:
\a alarm (beep)
\e escape
[:blank:]
whitespace [ \t]
\f formfeed
\n newline
[:cntrl:]
control characters
\r carriage return
\t tab
[:digit:]
digits
\cx control-x
\l lowercase next char
[:graph:]
alphanum + punctuation
\L lowercase until \E
\U uppercase until \E
[:lower:]
lowercase chars
\Q diable metachars
\E end case
[:print:]
alphanum, punct, space
until \E
modifications
[:punct:]
punctuation
[:space:]
whitespace [\s\ck]
Character Classes:
[amy]
'a', 'm', or 'y'
[:upper:]
uppercase chars
[f-j.-]
range f-j, dot, and dash
[:word:]
alphanum + '_'
[^f-j]
everything except range
[:xdigit:]
hex digit
[:^digit:]
non-digit
f-j
\d, \D
digit [0-9] / non-digit
no)
(?
condition corresponding to look-
(cond)yes)
around
Variables
$&
entire matched string
$`
everything prior to matched string
$'
everything after matched string
$1, $2 ...
n-th captured expression
$+
last parenthesis pattern match
$^N
most recently closed capt.
$^R
result of last (?{...})
@-, @+
offsets of starts / ends of groups
http://perldoc.perl.org/perlrequick.html
http://habrahabr.ru/post/17126/
Extended Constructs
(?#text)
comment
(?imxs-
enable or disable option
imsx:...)
(?=...),
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 Interaction (cont)
5 Input/Output (cont)
use re 'taint';
File Tests:
open(PRC,"caesar <$file
read from
|");
process
open(EXTRACT, "|sort
write to process
# Contents of $match are tainted if $dirty was
also tainted.
($match) = ($dirty =~ /^(.*)$/s);
# Allow code interpolation:
use re 'eval';
$pat = '(?{ $var = 1 })'; # embedded code
execution
/alpha${pat}omega/; # won't fail unless under -T
# and $pat is tainted
-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
use re 'debug'; # like "perl -Dr"
/^(.*)$/s; # output debugging info during
# compile time and run time
use re 'debugcolor'; # same as 'debug',
# but with colored output
4 System Interaction
system(cat $f|sort -
system call
u>$f.s);
@a = readpipe(lsmod);
catch output
$today = Today: .date;
catch output
better: use IPC::Open3 'open3';!
chroot(/home/user/);
change root
while (<*.c>) {}
operate on all cfiles
unlink(/tmp/file);
delete file
if (-f file.txt){...}
file test
@stats =
13-element list with
stat(filename);
status
File Tests in Perl
http://www.devshed.co
$line = <INFILE>;
get next line
@lines = <INFILE>;
slurp infile
foreach $line
loop of lines from
(<STDIN>){...}
STDIN
print STDERR "Warning
print to STDERR
1.\n";
close INFILE;
close filehandle
More:
m/c/a/Perl/File-Tests-
binmode, dbmopen,
select, syscall,
in-Perl/
dbmclose, fileno, flock,
sysreed, sysseek,
format, getc, read, readdir,
tell,
readline, rewinddir, seek,
telldir,truncate,
seekdir
pack, unpack,
More:
chmod, chown,
opendir, readlink,
chroot, fcntl, glob,
rename, rmdir,
ioctl, link, lstat, mkdir,
symlink, umask, utime
vec
7 Object-Oriented Perl and Modules
5 Input/Output
open(INFILE,"in.txt") or
>Tmp$$");
open file for input
die;
Defining a new class:
package Person;
use strict;
open(INFILE,"<:utf8","fil
open file with
my $Census;
e");
encoding
sub new { #constructor, any name is fine
open(TMP, "+>",
open anonymous
my $class = shift;
undef);
temp file
open(MEMORY,'>',
open in-memory-file
\$var);
open(OUT,">out.txt") or
open output file
die;
open(LOG,">>my.log")
my $self = {};
$self->{NAME} = undef; # field
$self->{"_CENSUS"} = \$Census; # class data
++ ${ $self->{"_CENSUS"} };
bless ($self, $class);
return $self;
open file for append
or die;
sub name { #method
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
my $self = shift;
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via cheatography.com/1008/cs/399/
7 Object-Oriented Perl and Modules (cont)
8 One-Liners (cont)
8 One-Liners (cont)
if (@_) { $self->{NAME} = shift }
-p
-l
return $self->{NAME};
}
sub DESTROY { #destructor
my $self = shift; -- ${$self->{"_CENSUS"} };}
Interactive
http://szabgab.com/using-the-
prints any warning messages.
repl.html
-e
indicates that the following string
debugger
/perl-debugger/
printf "There's someone named %s.\n", $him-
The Perl
http://docstore.mik.ua/orelly/perl/pro
Debugger
g3/ch20_01.htm
-T
enables taint checking, which
instructs perl to keep track of data
http://www.codeproject.com/Articles/3152/Perl-
from the user and avoid doing
Object-Oriented-Programming
anything insecure with it. Here this
http://ynonperek.com/course/perl/oo.html
option is used to avoid taking the
commands).
http://perldoc.perl.org/perlrun.html
Perl flags -
perl -e '$x = "Hello world!n"; print
pe, -pi, -p,
$x;'
-w, -d, -i, t? perldoc
perlrun
perl -MO=Deparse -p -e 1
perl -MO=Deparse -p -i -e 1
available .pm files from the
perl -MO=Deparse -p -i.bak -e 1
directory recursively.
https://twitter.com/#!/perloneliner
8 One-Liners
(zero) specify the input record separator
Examples:
1. just lines 15 to 17, efficiently
split data into an array named @F
perl -ne 'print if $. >= 15; exit if $. >= 17;'
a
-
script (i.e., sequence of
@INC variable and listing the
perl -MCPAN -e shell;
is to be interpreted as a perl
current directory name from the
Installing Modules:
each line.
-w
$him->name("Jason");
debug
separator (\n) added at the end of
built-in-debugger-of-perl-ashttp://www.thegeekstuff.com/2010/05
use Data::Dumper; print Dumper($him); #
statements will have the new line
perl -de1;use Term::ReadKey;
perl-
>name;
processing in the output. Print
Mode:
Using the class:
$him = Person->new();
enables automatic line-ending
contents of $_
1; # so the require or use succeeds
use Person;
same as -n, but will also print the
2. just lines NOT between line 10 and 20
specify pattern for -a to use when splitting
perl -ne 'print unless 10 .. 20'
-i
edit files in place
run through all the @ARGV arguments as
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
perl -ne 'print if /START$/ .. / END$/'
4. in-place edit of *.c files changing all foo to
bar
perl -pi.bak -e 's/\bfoo\b/bar/g' *.c
5. delete first 10 lines
perl -i.old -ne 'print unless 1 .. 10' foo.txt
6. change all the isolated oldvar occurrences to
newvar
CPAN, then you will need to re-install all of
them. (Naveed Massjouni)
perl -E 'say for grep /site_perl/,@INC'| xargs
find | perl -Fsite_perl/ -lane 'print $F[1] if
/\.pm$/' | cpanm --reinstall
15. Give executable rights to all perl file in dir
find /home/client0/public_html -type f -name
'*.pl' -print0 | xargs -0 chmod 0755
16. Find files matching name-pattern
perl -i.old -pe 's{\boldvar\b}{newvar}g' *.[chy]
7. printing each line in reverse order
perl -e 'print reverse <>' file1 file2 file3 ....
https://gist.github.com/563679
perl -MFile::Find -le 'find(sub{print
$File::Find::name if /\b[a-z]{2}_[A-Z]
{2}/},"/usr")'
8. find palindromes in the /usr/dict/words
dictionary file
perl -lne '$_ = lc $_; print if $_ eq reverse'
/usr/dict/words
9. command-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/(.
{50,72})\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/\.txt(\.out)$/$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