Perl Reference Card

ADVERTISEMENT

Perl Reference Card
1.3 Hashes
4 System Interaction
%h=(k1 => “val1”,k2 => 3);
hash initialization
system(“cat $f|sort -u>$f.s”); system call
This is version 2 of the perl reference card.
$val = $map{k1};
recall value
(cl) 2008 Michael Goerz <goerz@physik.fu-berlin.de>.
@a = readpipe(“lsmod”);
catch output
@a = %h;
array of keys and values
$today = “Today: “.`date`;
catch output
Information taken liberally from the perl documentation and various other sources.
%h = @a;
create hash from array
chroot(“/home/user/”);
change root
You may freely distribute this document.
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
defined $h{k1}
is key defined?
1.1 Scalars and Strings
-x
executable
-e
exists
chomp($str);
discard trailing \n
-f, -d, -l
is file, directory, symlink
$v = chop($str);
$v becomes trailing char
-T, -B
text file, binary file
eq, ne, lt, gt, le, ge, cmp
string comparison
2 Basic Syntax
-M, -A
mod/access age in days
$str = “0” x 4;
$str is now “0000”
@stats = stat(“filename”);
13-element list with status
($a, $b) = shift(@ARGV);
read command line params
$v = index($str, $x);
find index of $x in $str,
More: chmod, chown, chroot, fcntl, glob, ioctl, link,
sub p{my $var = shift; ...} define subroutine
$v = rindex($str, $x);
starting from left or right
lstat, mkdir, opendir, readlink, rename, rmdir,
p(“bla”);
execute subroutine
$v = substr($str, $strt, $len);
extract substring
symlink, umask, utime
if(expr){} elsif {} else {} conditional
$cnt = $sky =~ tr/0-9//;
count the digits in $sky
unless (expr){}
negative conditional
$str =~ tr/a-zA-Z/ /cs;
change non-alphas to space
while (expr){}
while-loop
$v = sprintf(“%10s %08d”,$s,$n); format string
until (expr){}
until-loop
Format String: %[flags][0][width][.precision][mod]type
5 Input/Output
do {} until (expr)
postcheck until-loop
types:
for($i=1; $i<=10; $i++){}
for-loop
c
character
open(INFILE,"in.txt") or die;
open file for input
foreach $i (@list){}
foreach-loop
d(i)
signed decimal int
open(INFILE,"<:utf8","file");
open file with encoding
last, next, redo
end loop, skip to next, jump to top
e(E)
scientific notation
open(TMP, "+>", undef);
open anonymous temp file
eval {$a=$a/$b; };
exception handling
f
decimal floating point
open(MEMORY,'>', \$var);
open in-memory-file
warn $@ if $@;
g, G
shorter %e or %f / %E or %f
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
3 References and Data Structures
p
address pointer
$line
= <INFILE>;
get next line
n
nothing printed
@lines
= <INFILE>;
slurp infile
$aref = \@a;
reference to array
modifiers: h,l,L
arg is short int / long int, double/ long double
foreach $line (<STDIN>){...}
loop of lines from STDIN
$aref = [1,"foo",undef,13]; anonymous array
More: chr, crypt, hex, lc, lcfirst, length, oct, ord,
print STDERR "Warning 1.\n";
print to STDERR
$el = $aref->[0];
access element of array
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,
$href = \%h;
reference to hash
format, getc, read, readdir, readline, rewinddir,
1.2 Arrays and Lists
$href ={APR => 4,AUG => 8}; anonymous hash
seek, seekdir, select, syscall, sysreed, sysseek,
@a = (1..5);
array initialization
$el = $href->{APR};
access element of hash
tell, telldir,truncate, pack, unpack, vec
$i = @a;
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;
last index in @a
6 Regular Expressions
@a = ([1, 2],[3, 4]);
2-dim array
push(@a, $s);
appends $s to @a
($var =~ /re/), ($var !~ /re/) matches / does not match
$i = $a[0][1];
access 2-dim array
$a = pop(@a);
removes last element
m/pattern/igmsoxc
matching pattern
%HoA=(fs=>["f","b"],
hash of arrays
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
e
as single line (. matches \n)
evaluate replacement
@a2 = grep(!/^#/, @a);
remove comments from @a
return sub {
print "$c++"; }; }
*foo{THING}
foo-syntax for creating refs

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2