Perl Cheat Sheet

ADVERTISEMENT

Perl Cheat Sheet
Functions
Get information on a function by typing, e.g.,
at the command line.
perldoc -f chomp
Scalar
while (defined ($x=<>)) {code}
False if variable has never been set (or when you
try to read past the end of an input file)
variables
length($x)
Length of a string
chomp($line);
Remove a newline at the end of a string
$short=substr ($long, 2, 5)
Characters 3-7 of $long (first char is 0!)
Arrays
push @arr, $x
Add to end of array
$x = pop @arr;
Remove last element of array, put in $x
shift @arr; (See also unshift)
Remove first element of an arrray, put in $x
$size = scalar @arr;
Number of things in the array
See also: split, join,
split string->array, join array->string,
splice, sort
delete part of array, sort array in many ways
Hashes
@key = keys %hash
The lookup terms in the hash
if (exists $hh{“Hsp”}) {...}
See whether hash %hh has a value for key Hsp
Input/Output
open(HANDLE, ">outfile") or
Open outfile for writing, and associate it with
die “Can’t open $outfile: $!\n”
filehandle HANDLE. Use “<infile” for reading
and Files
print $x;
Prints to standard output (screen),
print HANDLE $x;
Print to filehandle HANDLE
warn “Something wrong\n”;
Prints to standard error (screen)
$x=<HANDLE>
Read a line from filehandle HANDLE, put in $x
close(HANDLE);
Stop reading/writing a previously opened file
Exit
exit;
Exits the program
die "Something broke!\n";
Exits the program with error message
Operators and Loops
Assign
$x = 1
Sets variable to a value. Don’t confuse with ==,
which tests whether numerical values are equal
value
Math
print 1 * (2 + 3/4)
Regular math symbols
10%3==1; 12%3==0
Modulus (remainder) operator
$x += 4;
Same as $x=$x+4; Also -= *= /=
$x++;
Same as $x=$x+1;
Conditions
if (.1 == 0.1) {print “same num”}
Are numbers equal? Don’t confuse with = or eq
if (1 != 2) {print “diff num”}
Are numbers different?
> < >= <=
Are numbers greater than, less than, etc.
if (“a” eq “a”) {print “same text”}
Does text have exactly the same letters?
if (“A” ne “a”) {print “diff text”}
Does text have different letters?
if (($x > 1) && ($x < 2)) {code}
Logical AND (true if both sides are true)
if (($x > 10) || ($x < -10)) {code}
Logical OR (true if one or both sides are true)
=~ !~
Test for a match: See Matching cheat sheet
Loops
foreach my $i (1 .. 100) {code}
Sets $i to 1 and does code. Sets $i to 2, …
(for and foreach are equivalent)
up to (and including) 100
while ($a < $b) {code}
Does code while the condition is true
(If condition is false, never enters the loop.)

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 2