You are on page 1of 6

Perl Reference Card Cheat Sheet

by Nikolay Mishin (mishin) via

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

This is version 2 of the perl reference card. f decimal floating point @a = split(/-/,$s); split string into @a
(cl) 2008 Michael Goerz <goerz@physik.fu- g, G shorter %e or %f / $s = join(, @c); join @a elements into>. %E or %f string
o signed octal @a2 = array slice
Information taken liberally from the perl
s string of chars @a[1,2,6..9];
documentation and various other sources.
You may freely distribute this document. @a2 = grep(!/^#/, remove comments from
u, x, X unsigned decimal int /
hex int / hex int in @a); @a

1 Variable Types caps

Perl image
p address pointer
1.1 Scalars and Strings n nothing printed
chomp($str); discard trailing \n modifiers: h,l,L arg is short int / long
$v = chop($str); $v becomes trailing int, double/ long
char double

eq, ne, lt, gt, le, ge, string comparison More:

cmp chr, crypt, hex, lc, q/STRING/,
$str = 0 x 4; $str is now 0000 lcfirst, length, oct, ord, qq/STRING/, reverse,
pack uc, ucfirst
$v = index($str, $x); find index of $x in $str,

$v = rindex($str, $x); starting from left or right

1.2 Arrays and Lists
$v = substr($str, extract substring
@a = (1..5); array initialization
$strt, $len);
$i = @a; number of elements
$cnt = $sky =~ tr/0- count the digits in $sky
in @a
9//; 1.3 Hashes
($a, $b) = ($b, $a); swap $a and $b
$str =~ tr/a-zA-Z/ change non-alphas to
%h=(k1 => val1,k2 hash initialization
/cs; space $x = $a[1]; access to index 1
=> 3);
$v = sprintf(%10s format string $i = $#a; last index in @a
$val = $map{k1}; recall value
%08d,$s,$n); push(@a, $s); appends $s to @a
@a = %h; array of keys and
Format String: %[flags][0] $a = pop(@a); removes last values
[width][.precision][mod]ty element
pe %h = @a; create hash from array
chop(@a); remove last char
types: foreach $k iterate over list of keys
(per el.)
c character $a = shift(@a); removes first
foreach $v iterate over list of
d(i) signed decimal int element
(vals(%h)){..} values
e(E) scientific notation reverse(@a); reverse @a
while (($k,$v)=each iterate over key-
@a = sort{$ela <=> sort numerically
%h){..} value-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 = anonymous array


$el = $aref->[0]; $el = access element of

@{$aref}[0]; array

$aref2 = [@{$aref1}]; copy array

$href = \%h; reference to hash

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by Last updated 5th June, 2014. Measure your website readability! Page 1 of 6.
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via

3 References and Data Structures (cont) Link to perl cheat (cont) 6 Regular Expressions (cont)

$href ={APR => 4,AUG => 8}; anonymous 20-killer-perl-programming-tips Syntax:

\ escape
$el = $href->{APR}; $el = % access sheets/20-killer-perl-programming-tips-
. any single char
{$href}{APR}; element of for-beginners/
^ start of line
2 Basic Syntax $ end of line
$href2 = {%{$href1}}; copy hash
($a, $b) = read command line ,? 0 or more times (greedy /
if (ref($r) eq "HASH") {} checks if $r
shift(@ARGV); params nongreedy)
points to hash
sub p{my $var = shift; define subroutine +, +? 1 or more times (greedy /
@a = ([1, 2],[3, 4]); 2-dim array
...} nongreedy)
$i = $a[0][1]; access 2-dim
p(bla); execute subroutine ?, ?? 0 or 1 times (greedy / nongreedy)
if(expr){} elsif {} else {} conditional \b, \B word boundary ( \w - \W) / match
%HoA=(fs=>["f","b"], sp=> hash of arrays
except at w.b.
["h","m"]); unless (expr){} negative conditional
\A string start (with /m)
$name = $HoA{sp}[1]; access to while (expr){} while-loop
hash of arrays \Z string end (before \n)
until (expr){} until-loop
$fh = *STDIN globref \z absolute string end
do {} until (expr) postcheck until-loop
$coderef = \&fnc; code ref (e.g. \G continue from previous m//g
for($i=1; $i<=10; $i++) for-loop
callback) [...] character set
$coderef =sub{print "bla"}; anon (...) group, capture to $1, $2
foreach $i (@list){} foreach-loop
last, next, redo end loop, skip to next, (?:...) group without capturing
&$coderef(); calling anon
jump to top {n,m} , at least n times, at most m times
eval {$a=$a/$b; }; exception handling {n,m}?
sub createcnt{ my $c=shift; closure, $c
warn $@ if $@; {n,} , {n,}? at least n times
return sub { print "$c++"; }; } persists
{n} , {n}? exactly n times
*foo{THING} foo-syntax for
6 Regular Expressions
creating refs | or
($var =~ /re/), ($var !~ matches / does not
\1, \2 text from nth group ($1, ...)
/re/) match
Link to perl cheat Escape Sequences:
m/pattern/igmsoxc matching pattern
perlcheat \a alarm \e escape qr/pattern/imsox store regex in
sheets/perlcheat/ variable
\f \n newline
perl-reference-card s/pattern/replacement/ig search and replace
formfeed msoxe

sheets/perl-reference-card/ Modifiers:

i case-insensitive o compile once

g global x extended

s as single line (. e evaluate

matches \n) replacement

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by Last updated 5th June, 2014. Measure your website readability! Page 2 of 6.
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via

6 Regular Expressions (cont) 6 Regular Expressions (cont) 6 Regular Expressions (cont)

\r carriage \t tab [:punct:] punctuation $^R result of last (?{...})

return [:space:] whitespace [\s\ck] @-, @+ offsets of starts / ends of groups
\cx control-x \l lowercase next char [:upper:] uppercase chars
\L lowercase \U uppercase until \E
[:word:] alphanum + '_'
until \E
[:xdigit:] hex digit
\Q diable \E end case modifications Debugging regexp
[:^digit:] non-digit
metachars until
\E Extended Constructs use re 'taint';
# Contents of $match are tainted if $dirty was
Character Classes: (?#text) comment
also tainted.
[amy] 'a', 'm', or 'y' (?imxs- enable or disable option ($match) = ($dirty =~ /^(.*)$/s);
imsx:...) # Allow code interpolation:
[f-j.-] range f-j, dot, and dash
(?=...), positive / negative look-ahead use re 'eval';
[^f-j] everything except range f-j
(?!...) $pat = '(?{ $var = 1 })'; # embedded code
\d, \D digit [0-9] / non-digit execution
(?<=..), (? positive / negative look-behind
\w, \W word char [a-zA-Z0-9_] / non- /alpha${pat}omega/; # won't fail unless under -T
word char # and $pat is tainted
(?>...) prohibit backtracking use re 'debug'; # like "perl -Dr"
\s, \S whitepace [ \t\n\r\f] / non-
(?{ code embedded code /^(.*)$/s; # output debugging info during
}) # compile time and run time
\C match a byte use re 'debugcolor'; # same as 'debug',
(??{ code dynamic regex
\pP, \PP match p-named unicode / # but with colored output
(? condition corresponding to
\p{...}, \P{...} match long-named unicode / 4 System Interaction
(cond)yes| captured parentheses
non-named-unicode no) system(cat $f|sort -u>$f.s); system call
\X match extended unicode (? condition corresponding to look- @a = readpipe(lsmod); catch output
Posix: (cond)yes) around
$today = Today: .date; catch output
[:alnum:] alphanumeric Variables better: use IPC::Open3 'open3';!
[:alpha:] alphabetic $& entire matched string chroot(/home/user/); change root
[:ascii:] any ASCII char $` everything prior to matched string

[:blank:] whitespace [ \t] $' everything after matched string

[:cntrl:] control characters $1, $2 ... n-th captured expression

[:digit:] digits $+ last parenthesis pattern match

[:graph:] alphanum + punctuation $^N most recently closed capt.

[:lower:] lowercase chars

[:print:] alphanum, punct, space

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by Last updated 5th June, 2014. Measure your website readability! Page 3 of 6.
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via

4 System Interaction (cont) 5 Input/Output (cont) 7 Object-Oriented Perl and Modules (cont)

while (<*.c>) {} operate on all c-files open(OUT,">out.txt") or open output file sub name { #method

unlink(/tmp/file); delete file die; my $self = shift;

if (@_) { $self->{NAME} = shift }
if (-f file.txt){...} file test open(LOG,">>my.log") or open file for
die; append return $self->{NAME};
File Tests: }
open(PRC,"caesar <$file read from
-r, -w readable, writeable sub DESTROY { #destructor
|"); process
my $self = shift; -- ${$self->{"_CENSUS"} };}
-x executable
open(EXTRACT, "|sort write to process 1; # so the require or use succeeds
-e exists >Tmp$$"); Using the class:
-f, -d, -l is file, directory, $line = <INFILE>; get next line use Person;
symlink $him = Person->new();
@lines = <INFILE>; slurp infile
-T, -B text file, binary file
foreach $line loop of lines from printf "There's someone named %s.\n", $him-
-M, -A mod/access age in (<STDIN>){...} STDIN >name;
days use Data::Dumper; print Dumper($him); #
print STDERR "Warning print to STDERR
@stats = 13-element list with 1.\n"; debug
stat(filename); status
close INFILE; close filehandle
File Tests in Perl
in-Perl/ binmode, dbmopen, select, syscall,
dbmclose, fileno, flock, sysreed, sysseek, Installing Modules:
format, getc, read, readdir, tell,
chmod, chown, opendir, readlink, perl -MCPAN -e shell;
readline, rewinddir, seek, telldir,truncate,
chroot, fcntl, glob, rename, rmdir, seekdir pack, unpack,
ioctl, link, lstat, mkdir, symlink, umask, utime vec 8 One-Liners

- (zero) specify the input record separator

5 Input/Output 7 Object-Oriented Perl and Modules 0

open(INFILE,"in.txt") open file for input Defining a new class: - split data into an array named @F
or die; package Person; a

open(INFILE,"<:utf8","fil open file with use strict; - specify pattern for -a to use when splitting
e"); encoding my $Census; F
sub new { #constructor, any name is fine
open(TMP, "+>", open anonymous -i edit files in place
my $class = shift;
undef); temp file - run through all the @ARGV arguments as
my $self = {};
open(MEMORY,'>', open in-memory-file $self->{NAME} = undef; # field n files, using <>
\$var); $self->{"_CENSUS"} = \$Census; # class data - same as -n, but will also print the contents
++ ${ $self->{"_CENSUS"} }; p of $_
bless ($self, $class);
return $self;

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by Last updated 5th June, 2014. Measure your website readability! Page 4 of 6.
Perl Reference Card Cheat Sheet
by Nikolay Mishin (mishin) via

8 One-Liners (cont) 8 One-Liners (cont) Examples: (cont)

Interactive perl -de1;use Term::ReadKey; -w prints any warning messages. 7. printing each line in reverse order
Mode: -e indicates that the following perl -e 'print reverse <>' file1 file2 file3 .... string is to be interpreted as a 8. find palindromes in the /usr/dict/words

built-in-debugger-of-perl-as- perl script (i.e., sequence of dictionary file
repl.html commands). perl -lne '$_ = lc $_; print if $_ eq reverse'

perl- /usr/dict/words

debugger /perl-debugger/ Perl flags -pe, perl -e '$x = "Hello world!n"; 9. command-line that reverses all the bytes in a

The Perl -pi, -p, -w, -d, print $x;' file

Debugger g3/ch20_01.htm -i, -t? perldoc perl -0777e 'print scalar reverse <>' f1 f2 f3

-T enables taint checking, which perlrun 10. word wrap between 50 and 72 chars

instructs perl to keep track of data perl -MO=Deparse -p -e 1 perl -p000e 'tr/ \t\n\r/ /; s/(.

from the user and avoid doing {50,72})\s/$1\n/g;$_.="\n"x2'

perl -MO=Deparse -p -i -e 1
anything insecure with it. Here this 11. strip and remove double spaces
perl -MO=Deparse -p -i.bak -e
option is used to avoid taking the perl -pe '$_ = " $_ "; tr/ \t/ /s; $_ =
current directory name from the substr($_,1,-1)'
@INC variable and listing the!/perloneliner
12. move '.txt.out' to '.out'
available .pm files from the perl -e '($n = $_) =~ s/\.txt(\.out)$/$1/ and
directory recursively. Examples: not -e $n and rename $_, $n for @ARGV' *
-l enables automatic line-ending 1. just lines 15 to 17, efficiently 13. write a hash slice, which we have come as
processing in the output. Print perl -ne 'print if $. >= 15; exit if $. >= 17;' a reference to a hash
statements will have the new line perl -E'my $h={1..8}; say for @{$h}
2. just lines NOT between line 10 and 20
separator (\n) added at the end of {1,3,5,7}'
perl -ne 'print unless 10 .. 20'
each line.
14. If you had installed any modules from
3. lines between START and END
perl -ne 'print if /START$/ .. / END$/' CPAN, then you will need to re-install all of
them. (Naveed Massjouni)
4. in-place edit of *.c files changing all foo to
perl -E 'say for grep /site_perl/,@INC'| xargs
find | perl -Fsite_perl/ -lane 'print $F[1] if
perl -pi.bak -e 's/\bfoo\b/bar/g' *.c
/\.pm$/' | cpanm --reinstall
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/client0/public_html -type f -name
6. change all the isolated oldvar occurrences to '*.pl' -print0 | xargs -0 chmod 0755
16. Find files matching name-pattern
perl -i.old -pe 's{\boldvar\b}{newvar}g' *.[chy]
perl -MFile::Find -le 'find(sub{print
$File::Find::name if /\b[a-z]{2}_[A-Z]

By Nikolay Mishin (mishin) Published 2nd June, 2012. Sponsored by Last updated 5th June, 2014. Measure your website readability! Page 5 of 6.