Show Menu
Cheatography

Perl Reference Card Cheat Sheet by

This is version 2 of the perl reference card.

About

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>.
http:/­/ww­w.p­hys­ik.f­u-­ber­lin.de/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 \n
$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

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
Modifiers:
i case-i­nse­nsitive
o compile once
g global
x extended
s as single line (. matches \n)
e evaluate replac­ement
Syntax:
\
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 \n)
\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 Sequences:
\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
Character 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\n\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 Constructs
(?#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
Variables
$&
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

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
More:
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
More:
binmode, dbmopen, dbmclose, fileno, flock, format, getc, read, readdir, readline, rewinddir, seek, seekdir
select, 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();
$him->­nam­e("J­aso­n");
printf "­There's someone named %s.\n", $him->­name;
use Data::­Dumper; print Dumper­($him); # debug

http:/­/ww­w.c­ode­pro­jec­t.c­om/­Art­icl­es/­315­2/P­erl­-Ob­jec­t-O­rie­nte­d-P­rog­ramming
http:/­/yn­onp­ere­k.c­om/­cou­rse­/pe­rl/­oo.html

Installing Modules:

perl -MCPAN -e shell;

8 One-Liners

-0
(zero) specify the input record separator
-a
split data into an array named @F
-F
specify pattern for -a to use when splitting
-i
edit files in place
-n
run through all the @ARGV arguments as files, using <>
-p
same as -n, but will also print the contents of $_
Intera­ctive Mode:
perl -de1;use Term::­Rea­dKey;
 
perl-d­ebugger
The Perl Debugger
-T
enables 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.
-l
enables automatic line-e­nding processing in the output. Print statements will have the new line separator (\n) added at the end of each line.
-w
prints any warning messages.
-e
indicates 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 perlrun
perl -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

Examples:

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­ist.gi­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­")'
           
 

Comments

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet
          perlcheat Cheat Sheet

          More Cheat Sheets by mishin

          perlcheat Cheat Sheet
          Perl, short version Cheat Sheet