Show Menu

Perl Reference Card Cheat Sheet by mishin

This is version 2 of the perl reference card.


This is version 2 of the perl reference card.
(cl) 2008 Michael Goerz <go­erz­@ph­ysi­k.f­u-b­erl­in.d­e>.
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 \n
$v = chop($­str);$v becomes trailing char
eq, ne, lt, gt, le, ge, cmpstring 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
d(i)signed decimal int
e(E)scientific notation
fdecimal floating point
g, Gshorter %e or %f / %E or %f
osigned octal
sstring of chars
u, x, Xunsigned decimal int / hex int / hex int in caps
paddress pointer
nnothing printed
modifiers: h,l,Larg is short int / long int, double/ long double
chr, crypt, hex, lc, lcfirst, length, oct, ord, packq/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 = *STDINglobref
$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

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, redoend 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­msoxcmatching pattern
qr/pat­ter­n/imsoxstore regex in variable
s/patt­ern­/re­pla­cem­ent­/ig­msoxesearch and replace
i case-i­nse­nsitiveo compile once
g globalx extended
s as single line (. matches \n)e evaluate replac­ement
.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, \Bword boundary ( \w - \W) / match except at w.b.
\Astring start (with /m)
\Zstring end (before \n)
\zabsolute string end
\Gcontinue 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
\1, \2text from nth group ($1, ...)
Escape Sequen­ces:
\a alarm (beep)\e escape
\f formfeed\n 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, \Ddigit [0-9] / non-digit
\w, \Wword char [a-zA-­Z0-9_] / non-word char
\s, \Swhitepace [ \t\n\r\f] / non-space
\Cmatch a byte
\pP, \PPmatch p-named unicode / non-p-­nam­ed-­unicode
\p{...}, \P{...}match long-named unicode / non-na­med­-un­icode
\Xmatch extended unicode
[:ascii:]any ASCII char
[:blank:]whitespace [ \t]
[:cntrl:]control characters
[:graph:]alphanum + punctu­ation
[:lower:]lowercase chars
[:print:]alphanum, punct, space
[:space:]whitespace [\s\ck]
[:upper:]uppercase chars
[:word:]alphanum + '_'
[:xdigit:]hex digit
Extended Constr­ucts
(?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
$&entire matched string
$`everything prior to matched string
$'everything after matched string
$1, $2 ...n-th captured expression
$+last parent­hesis pattern match
$^Nmost recently closed capt.
$^Rresult of last (?{...})
@-, @+offsets of starts / ends of groups

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, -wreadable, writeable
-f, -d, -lis file, directory, symlink
-T, -Btext file, binary file
-M, -Amod/access age in days
@stats = stat(“­fil­ena­me”);13-element list with status
File Tests in Perlhttp:/­/ww­w.d­evs­­m/c­/a/­Per­l/F­ile­-Te­sts­-in­-Perl/
chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir,opendir, readlink, rename, rmdir, symlink, umask, utime

5 Input/­Output

open(I­NFI­LE,­"­in.t­xt­") or die;open file for input
open(I­NFI­LE,­"­<:u­tf8­"­,"fi­le");open file with encoding
open(TMP, "­+>", undef);open anonymous temp file
open(M­EMO­RY,­'>', \$var);open in-mem­ory­-file
open(O­UT,­"­>ou­t.t­xt") or die;open output file
open(L­OG,­"­>>m­y.l­og") or die;open file for append
open(P­RC,­"­caesar <$file |");read from process
open(E­XTRACT, "­|sort >Tm­p$$­");write to process
$line = <IN­FIL­E>;get next line
@lines = <IN­FIL­E>;slurp infile
foreach $line (<S­TDI­N>)­{...}loop of lines from STDIN
print STDERR "­Warning 1.\n";print to STDERR
close INFILE;close filehandle
binmode, dbmopen, dbmclose, fileno, flock, format, getc, read, readdir, readline, rewinddir, seek, seekdirselect, syscall, sysreed, sysseek, tell, telldi­r,t­run­cate, pack, unpack, vec

7 Object­-Or­iented Perl and Modules

Defining a new class:
package Person;
use strict;
my $Census;
sub new { #const­ructor, any name is fine
my $class = shift;
my $self = {};
$self-­>{NAME} = undef; # field
$self-­>{"_­CEN­SUS­"} = \$Census; # class data
++ ${ $self-­>{"_­CEN­SUS­"} };
bless ($self, $class);
return $self;
sub name { #method
my $self = shift;
if (@_) { $self-­>{NAME} = shift }
return $self-­>{N­AME};
sub DESTROY { #destr­uctor
my $self = shift; -- ${$sel­f->­{"_C­ENS­US"} };}
1; # so the ‘require’ or ‘use’ succeeds

Using the class:
use Person;
$him = Person­->n­ew();
printf "­There's someone named %s.\n", $him->­name;
use Data::­Dumper; print Dumper­($him); # debug


Installing Modules:

perl -MCPAN -e shell;

8 One-Liners

-0(zero) specify the input record separator
-asplit data into an array named @F
-Fspecify pattern for -a to use when splitting
-iedit files in place
-nrun through all the @ARGV arguments as files, using <>
-psame as -n, but will also print the contents of $_
Intera­ctive Mode:perl -de1;use Term::­Rea­dKey;
The Perl Debuggerhttp:/­/do­cst­ore.mi­k.u­a/o­rel­ly/­per­l/p­rog­3/c­h20­_01.htm
-Tenables taint checking, which instructs perl to keep track of data from the user and avoid doing anything insecure with it. Here this option is used to avoid taking the current directory name from the @INC variable and listing the available .pm files from the directory recurs­ively.
-lenables automatic line-e­nding processing in the output. Print statements will have the new line separator (\n) added at the end of each line.
-wprints any warning messages.
-eindicates that the following string is to be interp­reted as a perl script (i.e., sequence of commands).
Perl flags -pe, -pi, -p, -w, -d, -i, -t? perldoc perlrunperl -e '$x = "­Hello world!­n"; print $x;'
 perl -MO=De­parse -p -e 1
 perl -MO=De­parse -p -i -e 1
 perl -MO=De­parse -p -i.bak -e 1


1. just lines 15 to 17, effici­ently
perl -ne 'print if $. >= 15; exit if $. >= 17;'
2. just lines NOT between line 10 and 20
perl -ne 'print unless 10 .. 20'
3. lines between START and END
perl -ne 'print if /START$/ .. /END$/'
4. in-place edit of *.c files changing all foo to bar
perl -pi.bak -e 's/\bf­oo\­b/b­ar/g' *.c
5. delete first 10 lines
perl -i.old -ne 'print unless 1 .. 10' foo.txt
6. change all the isolated oldvar occurr­ences to newvar
perl -i.old -pe 's{\bo­ldv­ar\­b}{­new­var}g' *.[chy]
7. printing each line in reverse order
perl -e 'print reverse <>' file1 file2 file3 ....
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}'
14. If you had installed any modules from CPAN, then you will need to re-install all of them. (Naveed Massjouni)
perl -E 'say for grep /site_­per­l/,­@INC'| xargs find | perl -Fsite­_perl/ -lane 'print $F[1] if /\.pm$/' | cpanm --rein­stall
15. Give executable rights to all perl file in dir
find /home/­cli­ent­0/p­ubl­ic_html -type f -name '*.pl' -print0 | xargs -0 chmod 0755
16. Find files matching name-p­attern https:­//g­­thu­b.c­om/­563679
perl -MFile­::Find -le 'find(­sub­{print $File:­:Fi­nd:­:name if /\b[a-­z]{­2}_­[A-­Z]{­2}/­},"/­usr­")'

Share This Cheat Sheet!

Favourited by 6 Members:

robertmorris carconper sam chen akipta sebbu mishin


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.