This covers Perl 5. Also see my regular expressions cheatsheet.
# Comments start with a hash.
$x = "A string"; print $x . ' ' . ' concatenated with dots.';
Initialize (clear) an array:
my @array = ();
Assign values to an array:
@array = ("foo", "bar", "bat");
Get value of an array element:
print $array[1];
Pushing and popping elements to or from the end of an array:
push (@array, $newElement); $x = pop (@array);
The functions shift() and unshift() do the same thing as push() and pop(), but to the beginning of an array.
Find length of array:
$arraySize = scalar (@array);
or:
$arraySize = $#array + 1;
Arrays can be sorted in a variety of ways:
@reversedArray = reverse (@array); @sortedAscendingArray = sort {$a <=> $b} @array; @sortedDescendingArray = sort {$b <=> $a} @array;
Create a hash:
my %hash = (); %hash = ( key0 => "value foo", key1 => "value bar", key2 => "value bat" );
Use hash:
print $hash{key1};
Check if hash element exists:
if (exists ($hash{'key1'})) { print "Hash key1 exists."; }
Add to a hash:
$hash{$key3} = "value bam";
Remove hash element:
delete ($hash{'key3'});
Iterate over a hash:
while (($key, $value) = each (%hash)) { print "$key and $value.\n"; }
Another couple of ways to loop over hashes:
foreach $key (keys %hash) { print $hash{$key}; } foreach $value (values %hash) { print $value; }
If/else conditionals:
if ($n == 1) { print "It's 1.\n"; } elsif ($n == 2) { print "It's 2.\n"; } else { print "It's not 1 or 2.\n"; }
for loop:
for ($i = 0; $i < 10; $i ++) { print "Count is $i.\n"; }
The foreach loop, looping over elements in an array:
foreach $element (@array) { print $element; }
Open a file, and read it:
open (INPUT, "<$inputFile") or die ("Can't open read input file $inputFile"); while (<INPUT>) { print $_; } close (INPUT);
Open a file, and write to it:
open (OUTPUT, ">$outputFile") or die ("Can't open output file $outputFile"); print OUTPUT $output; close (OUTPUT);
sub mysub { print "First subroutine argument is $_[0]\n"; }
Check if a module is installed by trying to open its documentation:
perldoc GD::Graph
Install modules using the CPAN shell:
perl -MCPAN -e shell
Find a module in CPAN:
cpan> i /GD/
Install a module using CPAN:
cpan> install GD::Graph
Round to two decimal places:
$rounded = sprintf ("%.2f", 100.23456);
This list is not exhaustive, but these are the ones I commonly use:
$_ | Current default value |
$! | Current error |
@ARGV | Command line arguments |
@_ | Subroutine arguments $_[0], $_[1], etc. |
$1 | $2, $3, etc.; Pattern matches |
$∓ | Last pattern match |
$. | Current input line number |
© Paul Gorman