Show Menu
Cheatography

Perl shortcuts Cheat Sheet by

Descriptive cheat sheet

Docume­ntation

=pod
my $dog = ”hatchi”;
my $cat = “meow”;
=cut

Logical Operators

Logical
or, and, xor, not, ||, &&, !
Strings
eq, gt, lt, le, ge, cmp
Numbers
==, <,>­,<=­,>=­,<=>

File Test Operators

-e exists
-r readable
-w writable
-d directory
-f file
-T Text file

Conditions

Unless
if { }
elsf{}
else{}
given() { when { } }

Regular expression

Whitespace
\s
word
\w
Digit
\d
Non digit
\D
Beginning
^
End
$
/\bFred\b/ matches whole word
Next LINE if $line=­/^#/;

Quanti­fiers

min, max
\d{min, max}
7 to 11 digit
\d{7,11}
Only matches 7 digit
\d{7}
+, *, ? .
{} quanti­fiers applies to single character
() store in memory
s/(S+)­s+(­S+)/$2 $1/

LIST processing

print reverse sort map{lc} keys %hash

To parse a string 12:59:59 am

-my ($hour, $min, $sec, $ampm)­=/(­\d+): (\d+) : (\d+) * (\w+)/

Terms and List Operator

|| has lower precedence than chdir
chdir $foo || die #(chdir $foo) || die
chdir(­$foo) || die #(chdir $foo) || die
chdir +($foo) || die #(chdir $foo) || die

Evalvu­ation

print(­$foo, exit) # Obviously not what you want
print $foo, exit #nor this
These do the print before evaluating exit.

(print $foo), exit
or
print ($foo), exit

File test operator

Total seconds /day = 86400
5 Minutes = 300
12 hour = 300 12 12 = 43200
Total hour= 12 hr/86400 = 0.5
-M $finename > 0.5 #greated than 12 hours
-M $finename > 0.5 #recently modified file
&c­all­fun­ction If int( -A $filename) == 90

Tricks

Sub setenv{
my ($key, $value)=@_;
$ENV{$key)=$value unless $ENV{$key}
}

Initia­liz­ation

BEGIN {
my @scale = ("A" .. "G");
my $note = –1;
sub next_pitch { return $scale[ ($note += 1) %= @scale ] }; }
It will execute before your program starts

Handle reference

for $file(@names){
my $fh;
open($fh, $file) || next;
$filehandle{$file}=$fh;
}

Symbol table reference

$scalarref= *foo{SCALAR} # \$foo
$arrayref=*ARGV{ARRAY}  # \@ARGV
$hashref = *ENV{HASH}; # \%ENV
$coderef=*handler{CODE} # \&handler
$gobref=*foo{GLOB}
$ioref=*STDIN{IO};
$format=*foo{FORMAT};

protection

use strict “refs”
block counterman the decree with
no strict “refs”

Symbolic reference example:

our $value = "global"; { 
my $value = "private";
print "Inside, mine is ${value}, "; say "but ours is ${"value"}."; 
}
say "Outside, ${value} is again ${"value"}.";
which prints:
Inside, mine is private, but ours is global. Outside, global is again global.

Package variables are global variable
 

Variables

$days : simple scalar value
$days[28] : 29 elements
$days{­“feb”} value from hash days

${day}. Equvalent to $day
$Dog;:day; from Dog package
$#days last index of array #days
$days-­>[28] 29 the element pointed to by reference
$days[­0][2] multi dim array
$days{­200­0}{­“feb”} mult dim hash
$days{­200­,”feb”} multi dimens­ional hash emulation
@days : array containing ($day[0], $day[1­]….$­da­y[N])
@days[­3,4,5] :array containing ($day[3], $day[4], 4day[5])
@days[­3..5]: array containing ($day[3], $day[4­],$­day[5])
@days{­“Jan”, “Feb”}: hash containing ($days­{“J­an”}, $days{­“feb”})
$days{­“feb”} equvalent to $days{feb}

Name space

Lexical scope: block
Symbol table : global

Tips:
$foo, @foo can be declared
In same block,
$foo[0] is different from $foo

Comman­dLine

Perl -E ‘say 10/3’;
Perl-M­bigrat. -E ‘sat 4/3. * 5/12’

Truth

String True except for “ “ and “0”
Number true except for 0
Any reference is true
Any undefined value is false.

Tips

$” is equal to space “ “
$temp=­joi­n($”, @array);
Or
$temp=­join(“ “, @array);

Quote Construct

q//
' '
qq//
" "
qx/ /
Command exec
qw//
WordList
m//
Pattern match
s//
Substitute
y///
Transl­ation
Qr//
Regular Expression

Auto Increment and Decrement

++$b{/­(\w­+)/­}[0]}
# increment the element hash indexed by word in the default
search variable ($_)and return after increment.
my $foo;
$foo= “99”; print ++ $foo ; #prints 100
$foo=”Az”; print ++ $foo ; #prints Ba

Binding operator

$string ! ~ /$pattern/
! ($string =~ /$patt­ern/)
not ($string =~ /$patt­ern/)
~ is after =

Equality Operator

cmp : return -1 if left operand is less than right, 0 If it is equal, 1 if left operand is greater than right.

smartwatch operator

my %hash = (red => 1, blue => 2, green => 3, orange => 4, yellow => 5, purple => 6,
black => 7, grey => 8, white => 9);
my @array = qw(red blue green);
print "some element in hash" if @array ~~ %hash;

Reference

@tailings=popmany(\@a, \@a2, \@a3);
Sub popmany{
my @retlist=()
for my $ref (@_) {
push @retlist @$ref;
}
return @retlist;
}
If you want to pass more than one array and hashes to the function you might have to use pass by reference, it saves the time and space

Hash of Hash

%table= (
         'john' => {age =>47, eyes=>'brown', weight=>186},
         'Mary'=>{age=>23, eyes=>'hazel', weight=>128}
        );

print $table{john}{age}
Prints 47

Operator: ref

Ref operator to determine what a reference is pointing.

SCALAR, ARRAY, HASH, CODE, GLOB, REF, VSTRING, IO, LVALUE, FORMAT, REGEXP

Symbolic reference

$name=”bam”;
$$name=1;   #sets $bam
$name->[0]=4;
 #set the first element of @bam
$name->{X}=”Y” #sets the X element of Y
@$name=() #resets the @bam
&$name  #calls the function bam
 

Status

$$ current process id
$? Exits status

Context

Scalar:
$x = funkshun()
$x[1] = funkshun()
$x{“ray”}= funkshun()

List:
@x= funksh­un();
@x[1]= funksh­un();
@ax{“r­ay”}= funkshun()
%x= funkshun()
($x, $y, $z)= funkshun()
($x)= funkshun()

my $x= funkshun() #scalar context
my ($x)= funksh­un(). # list context

Boolean:
@x; gives number of elements
While(@x){
$file=­Shi­ft(@x);
unlink­($file) || warn. “couldn’t delete file”;
}

List values and arrays

@stuff­=(“­one”, “two”, “three”)
Assign entire list to array
$stuff­=(“­one”, “two”, “three”)
“three” is assigned to stuff
$stuff­=@s­tuff;
$stuff is assigned to length of the array i.e 3
@relea­ses­=(“­alpha”, ”beta”, ”gamma”,)
Comma is allowed in the last.
$modif­ica­tio­nti­me=­(st­at(­$fi­le)­)[9];
Modifi­cation time
$hexdi­git­=(“­a”,­”b”­,”c­”,”­d”,­)[$­dig­it-10]
hexdigit
($day, $month, $year)­=(l­oca­lti­me)[3, 4,5];
day/mo­nth­/year
@days + 0;
implicit forces array into scalar
scalar­(@days)
explicit r @days into scalar
@whate­ver=()
$#what­ever=-1
undef(­@wh­atever)
recover its memory
scalar­(@w­hat­ever)
$# whatever + 1;

Multip­lic­ative operator

print “-“ x 80
prints row of dashes.
my @ones = (1) x 80;
list of 80 1’s;
@ones = (5) x @ones
#set all elements to 5

Array, Hash initia­liz­ation:

my %hash
@hash(­@keys) = (“ “) x @keys;
my @keys
@keys=qw( perl doc yyy);
Result:
$hash{­per­l}=””;
$hash{­doc­}=””;
$hash{­yyy}=””

Short circuit operator

$a && $b or $a and $b
$a || $b or $a or $b
$a // $b #define OR
$pid=fok() // die ‘’can’t fork $!’’
$value = $hash{­value} // “DEFAULT”

Condit­ional operator

my $a = $ok ? $a: $b
my @a=$ok? @a:@b;
( $a_or_b ? $a:$b)=$c

miscel­laneous

State : state variable is never initia­lized and restricted to scalar vairables.

use v5.18;
sub next_c­ount{
state $count­er=0;
return ++$cou­nter;
}
print (next_­cou­nt());
print (next_­cou­nt());
print (next_­cou­nt());

Output: 1,2,3

Our: access the global variable

sub check_­war­ehouse {
our @Curre­nt_­Inv­entory;
my $widget;
foreach $widget (@Curr­ent­_In­ven­tory) {
say "I have a $widget in stock today."­; }
}
our keyword changes the global variable
local: it changes the variable value locally even if it uses the global name and it will not change the gloal variable value.
Subrou­tines
To declare named subroutine without defining
Sub Name Sub Name Proto Sub Name Proto attr

Tricks2

@reflist = ( \$s, \@a, \%h)
         Is equal to 
@reflist=\($s, @a, %h)


@reflist=\(@x);
 Is equal to 
@reflist=map(\$_}@x;

@reflist = \fx();
Is equal to 
@reflist=map{\$_} fx();

@reflist=\(fx(), fy(), fz());
Is equal to 
@reflist=map{\$_} fx(), fy(), fz();


@reflist=\localtime(); #ref to each of nine time elements
$lastref = \localtime() #ref to whether it’s daylight saving time

variable as a a variable name

$$ref is scalar value of $ref refers to 
@$ref is array values of $ref refers to 
%$ref is hash values of $ref referes to 

$foo = “three humps”;
$scalarref = \$foo;
$camel_model= $$scalarref;
 
push(@$arrayref, $filename);

$$arrayref[0]=”Janualry” ; set the first element of @$arrayref;
@$arrayref[4…6] = qw /may June July/;

%$hashref = (KEY=>”RING”, BIRD=>”Sing”)
$$hashref{KEY}=”VALUE”;

@$hashref{“KEY1”, “KEY2”}=(“VAL1”, “VAL2”);

$refrefref=\\\”hody”;
print ($$$$refrefref);
Sigil => $ (dollar means sigil)
 

Hashes

my %map=(“aa”, 1, “bb”, 2);
  or
my %map=(aa=>1, bb=>2,);
 or
$map{aa}=1;
$map{bb}=2;
Reference:
 $map={ “aa”. => 1, “bb”=>2 }
Derefe­rence:
%m=%$map;
print(­$m{­aa});
Or
print(­$ma­p->­{aa});

Type glob and file handles

*foo contains values of $foo, @foo, %foo, $foo,
Typeglob stores entire symbol table entry

foo=bar;
It makes everything named foo. synonymous to every corres­ponding thing name bar
*foo=­\$bar;
Makes an foo an alias of bar but doesn’t make it for @foo an alias for @bar.

Backtic operator

$perl_­inf­o=qx(ps $$); #thats perl
$k =
ls
; Interp­reted in shell and store the result in $k
$shell­_in­fo=­qx’ps. $$’; #thats shell

Line Input Operator

While(­$_=­def­ine­d(<­STD­IN>)){
print } or
print $_ while define­d($­_=<­STD­IN>);

$one_l­ine­=<M­YFI­LE>
@allli­nes­=<M­YFI­LE>

Filename Globbing operator

@files =<*.xml>
    To
Filehandle in a variable 
<$foo>

@files=glob(*”.xml”);

while(glob *.c){
chmod 0644 $_
}
@files=gob(“$dir/*.[ch]”);

Statement

Loop Control:
last, next, redo

LINE:w­hil­e(<­STD­IN>){
last LINE if ~/^$/;
eval { }; print ($@) #captures error
Scoped variables :

Named Unary operators

To declare and define named sub routine

Sub Name Block
Sub Name Proto Block
Sub Name Proto attr Block
Subrou­tines without names:
save return values at compile time, but also returns value
$subref = sub Block;

To import subrou­tines

use MODULE qw(Name1 Name2 Name3)

call subroutine

Name(LIST)
& is optional with parameter or Name LIST
Name
exposes current @_ to that subroutine

Indirect call

&$­sub­ref­(LIST )
&$­sub­ref­->(­LIST),
&$­subref

Semantics

Sub razzle{
print “Ok”
}
Default parameter @_;
Which is local array
$_[0]., $_[1] are the first two elements of array

Inline constant function

sub FLAG_FOO () { 1 << 8 }
sub FLAG_BAR () { 1 << 9 }
sub FLAG_MASK () { FLAG_FOO | FLAG_BAR } 

sub OPT_GLARCH(){
{ (0x1B58 & FLAG_MASK) == 0 } {
{ return 23 }
{ return 42 } 
}

To return hash memory

Sub hashem{ +{@_} }
Sub hashem{ return{@_}}
Anonymous subroutine composer

$coderef = sub {print “Boink­!\n”};

Semicolon is to terminate $coderef;
Sub { } > code inside is not executed immedi­ately, it just generates reference to code.

References

References are like & in C

Anonymous hash with braces
$hashref={
“adam” => “eve”,
“clde”­=>$­bonnie
}

Hash of array

%table= (
'john' =>[47, 'brown',186],
'mary '=>[23, 'hazel', 128]
);

print @{$table{john}}[0];
prints 47
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Web Programming Cheat Sheet
          Perl Reference Card Cheat Sheet
          perlcheat Cheat Sheet

          More Cheat Sheets by Sathyanarayanan

          Linux Command Line Cheat Sheet