You are on page 1of 2

Perl Reference Card 1.

3 Hashes 4 System Interaction


This is version 2 of the perl reference card.
%h=(k1 => val1,k2 => 3); hash initialization system(cat $f|sort -u>$f.s); system call
(cl) 2008 Michael Goerz <goerz@physik.fu-berlin.de>. $val = $map{k1}; recall value @a = readpipe(lsmod); catch output
http://www.physik.fu-berlin.de/~goerz/ @a = %h; array of keys and values $today = Today: .`date`; catch output
Information taken liberally from the perl documentation and various other sources.
You may freely distribute this document.
%h = @a; create hash from array chroot(/home/user/); change root
foreach $k (keys(%h)){..} iterate over list of keys while (<*.c>) {} operate on all c-files
foreach $v (vals(%h)){..} iterate over list of values unlink(/tmp/file); delete file
while (($k,$v)=each %h){..} iterate over key-value-pairs if (-f file.txt){...} file test
1 Variable Types delete $h{k1}; delete key File Tests:
exists $h{k1} does key exist? -r, -w readable, writeable
1.1 Scalars and Strings defined $h{k1} is key defined? -x executable
chomp($str); discard trailing \n -e exists
$v = chop($str); $v becomes trailing char -f, -d, -l is file, directory, symlink
eq, ne, lt, gt, le, ge, cmp string comparison -T, -B text file, binary file
$str = 0 x 4; $str is now 0000 2 Basic Syntax -M, -A mod/access age in days
$v = index($str, $x); find index of $x in $str, ($a, $b) = shift(@ARGV); read command line params @stats = stat(filename); 13-element list with status
$v = rindex($str, $x); starting from left or right sub p{my $var = shift; ...} define subroutine More: chmod, chown, chroot, fcntl, glob, ioctl, link,
$v = substr($str, $strt, $len); extract substring p(bla); execute subroutine lstat, mkdir, opendir, readlink, rename, rmdir,
$cnt = $sky =~ tr/0-9//; count the digits in $sky if(expr){} elsif {} else {} conditional symlink, umask, utime
$str =~ tr/a-zA-Z/ /cs; change non-alphas to space unless (expr){} negative conditional
$v = sprintf(%10s %08d,$s,$n); format string while (expr){} while-loop
Format String: %[flags][0][width][.precision][mod]type until (expr){} until-loop
types: do {} until (expr) postcheck until-loop 5 Input/Output
c character for($i=1; $i<=10; $i++){} for-loop open(INFILE,"in.txt") or die; open file for input
d(i) signed decimal int foreach $i (@list){} foreach-loop open(INFILE,"<:utf8","file"); open file with encoding
e(E) scientific notation last, next, redo end loop, skip to next, jump to top open(TMP, "+>", undef); open anonymous temp file
f decimal floating point eval {$a=$a/$b; }; exception handling open(MEMORY,'>', \$var); open in-memory-file
g, G shorter %e or %f / %E or %f warn $@ if $@; open(OUT,">out.txt") or die; open output file
o signed octal open(LOG,">>my.log") or die; open file for append
s string of chars open(PRC,"caesar <$file |"); read from process
u, x, X unsigned decimal int / hex int / hex int in caps open(EXTRACT, "|sort >Tmp$$"); write to process
p address pointer 3 References and Data Structures $line = <INFILE>; get next line
n nothing printed $aref = \@a; reference to array @lines = <INFILE>; slurp infile
modifiers: h,l,L arg is short int / long int, double/ long double $aref = [1,"foo",undef,13]; anonymous array foreach $line (<STDIN>){...} loop of lines from STDIN
More: chr, crypt, hex, lc, lcfirst, length, oct, ord, $el = $aref->[0]; access element of array print STDERR "Warning 1.\n"; print to STDERR
pack, q/STRING/, qq/STRING/, reverse, uc, ucfirst $el = @{$aref}[0]; close INFILE; close filehandle
$aref2 = [@{$aref1}]; copy array More: binmode, dbmopen, dbmclose, fileno, flock,
1.2 Arrays and Lists $href = \%h; reference to hash format, getc, read, readdir, readline, rewinddir,
@a = (1..5); $href ={APR => 4,AUG => 8}; anonymous hash seek, seekdir, select, syscall, sysreed, sysseek,
array initialization
$i = @a; $el = $href->{APR}; access element of hash tell, telldir,truncate, pack, unpack, vec
number of elements in @a
$el = %{$href}{APR};
($a, $b) = ($b, $a); swap $a and $b
$href2 = {%{$href1}}; copy hash
$x = $a[1]; access to index 1 if (ref($r) eq "HASH") {} checks if $r points to hash
$i = $#a;
push(@a, $s);
last index in @a @a = ([1, 2],[3, 4]); 2-dim array 6 Regular Expressions
appends $s to @a $i = $a[0][1]; access 2-dim array ($var =~ /re/), ($var !~ /re/) matches / does not match
$a = pop(@a); removes last element %HoA=(fs=>["f","b"], hash of arrays m/pattern/igmsoxc matching pattern
chop(@a); remove last char (per el.) sp=>["h","m"]); qr/pattern/imsox store regex in variable
$a = shift(@a); removes first element $name = $HoA{sp}[1]; access to hash of arrays s/pattern/replacement/igmsoxe search and replace
reverse(@a); reverse @a $fh = \*STDIN globref Modifiers:
@a = sort{$ela <=> $elb}(@a); sort numerically $coderef = \&fnc; code ref (e.g. callback) i case-insensitive o compile once
@a = split(/-/,$s); split string into @a $coderef =sub{print "bla"}; anon subroutine g global x extended
$s = join(, @c); join @a elements into string &$coderef(); calling anon subroutine m multiline c don't reset pos (with g)
@a2 = @a[1,2,6..9]; array slice sub createcnt{ my $c=shift; closure, $c persists s as single line (. matches \n) e evaluate replacement
@a2 = grep(!/^#/, @a); remove comments from @a return sub {
print "$c++"; }; }
*foo{THING} foo-syntax for creating refs
Syntax:
\ escape
Extended Constructs
(?#text) comment
8 One-Liners
-0 (zero) specify the input record separator
. any single char (?imxs-imsx:...) enable or disable option -a split data into an array named @F
^ start of line (?=...), (?!...) positive / negative look-ahead -F specify pattern for -a to use when splitting
$ end of line (?<=..), (?<!..) positive / negative look-behind -i edit files in place
*, *? 0 or more times (greedy / nongreedy) (?>...) prohibit backtracking -n run through all the @ARGV arguments as files, using <>
+, +? 1 or more times (greedy / nongreedy) (?{ code }) embedded code -p same as -n, but will also print the contents of $_
?, ?? 0 or 1 times (greedy / nongreedy) (??{ code }) dynamic regex
\b, \B word boundary ( \w - \W) / match except at w.b. (?(cond)yes|no) condition corresponding to captured parentheses
Interactive Mode: perl -de 42
\A string start (with /m) (?(cond)yes) condition corresponding to look-around
\Z string end (before \n) Variables
$& Examples:
\z absolute string end entire matched string
$` 1. just lines 15 to 17, efficiently
\G continue from previous m//g everything prior to matched string perl -ne 'print if $. >= 15; exit if $. >= 17;'
[...] character set $' everything after matched string
2. just lines NOT between line 10 and 20
(...) group, capture to $1, $2 $1, $2 ... n-th captured expression perl -ne 'print unless 10 .. 20'
(?:...) group without capturing $+ last parenthesis pattern match
3. lines between START and END
{n,m} , {n,m}? at least n times, at most m times $^N most recently closed capt. perl -ne 'print if /^START$/ .. /^END$/'
{n,} , {n,}? at least n times $^R result of last (?{...})
4. in-place edit of *.c files changing all foo to bar
{n} , {n}? exactly n times @-, @+ offsets of starts / ends of groups perl -pi.bak -e 's/\bfoo\b/bar/g' *.c
| or 5. delete first 10 lines
\1, \2 text from nth group ($1, ...) perl -i.old -ne 'print unless 1 .. 10' foo.txt
Escape Sequences: 6. change all the isolated oldvar occurrences to newvar
\a alarm (beep) \e escape 7 Object-Oriented Perl and Modules perl -i.old -pe 's{\boldvar\b}{newvar}g' *.[chy]
\f formfeed \n newline 7. printing each line in reverse order
\r carriage return \t tab Defining a new class: perl -e 'print reverse <>' file1 file2 file3 ....
\cx control-x \l package Person;
lowercase next char 8. find palindromes in the /usr/dict/words dictionary file
\L \U use strict;
lowercase until \E uppercase until \E perl -lne '$_ = lc $_; print if $_ eq reverse'
sub new { #constructor, any name is fine /usr/dict/words
\Q diable metachars until \E \E end case modifications
my $class = shift;
Character Classes: 9. command-line that reverses all the bytes in a file
my $self = {}; perl -0777e 'print scalar reverse <>' f1 f2 f3
[amy] 'a', 'm', or 'y'
$self->{NAME} = undef; # field
[f-j.-] range f-j, dot, and dash 10. word wrap between 50 and 72 chars
$self->{"_CENSUS"} = \$Census; # class data perl -p000e 'tr/ \t\n\r/ /;
[^f-j] everything except range f-j
++ ${ $self->{"_CENSUS"} }; s/(.{50,72})\s/$1\n/g;$_.="\n"x2'
\d, \D digit [0-9] / non-digit
bless ($self, $class); 11. strip and remove double spaces
\w, \W word char [a-zA-Z0-9_] / non-word return $self; perl -pe '$_ = " $_ "; tr/ \t/ /s; $_ =
char }
\s, \S whitepace [ \t\n\r\f] / non-space substr($_,1,-1)'
sub name { #method 12. move '*.txt.out' to '*.out'
\C match a byte my $self = shift;
\pP, \PP match p-named unicode / non-p-named-unicode perl -e '($n = $_) =~ s/\.txt(\.out)$/$1/ and not
if (@_) { $self->{NAME} = shift } -e $n and rename $_, $n for @ARGV' *
\p{...}, \P{...} match long-named unicode / non-named-unicode return $self->{NAME};
\X match extended unicode }
Posix: sub DESTROY { #destructor
[:alnum] alphanumeric my $self = shift; -- ${$self->{"_CENSUS"} };}
[:alpha] alphabetic 1; # so the require or use succeeds
[:ascii:] any ASCII char
[:blank:] whitespace [ \t] Using the class:
[:cntrl:] control characters use Person;
[:digit:] digits $him = Person->new();
[:graph:] alphanum + punctuation $him->name("Jason");
[:lower:] lowercase chars printf "There's someone named %s.\n", $him->name;
[:print:] alphanum, punct, space use Data::Dumper; print Dumper($him); # debug
[:punct:] punctuation
[:space:] whitespace [\s\ck]
[:upper:] uppercase chars
[:word:] alphanum + '_'
[:xdigit:] hex digit
[:^digit:] non-digit Installing Modules: perl -MCPAN -e shell;

You might also like