Perl
Updated: September 10, 2025Categories: Languages
Printed from:
Perl Cheatsheet
Language Overview
Perl (Practical Extraction and Reporting Language) is a high-level, dynamic programming language known for its powerful text processing capabilities, flexibility, and "There's More Than One Way To Do It" (TMTOWTDI) philosophy. Originally developed by Larry Wall, Perl is widely used in system administration, web development, network programming, and bioinformatics. It combines features from C, shell scripting, awk, and sed, making it extremely versatile for scripting and rapid development.
Basic Syntax
perl
1234567891011121314# Single line comment
=pod
Multi-line comment
or documentation block
=cut
# Print statement
print "Hello, World!\n";
# Semicolons are required to end statements
my $variable = "value";
# Blocks use curly braces, not indentation
if ($condition) {
print "Condition is true";
}
Data Types
Scalars (Single Values)
perl
12345my $integer = 42; # Integer
my $float = 3.14; # Floating point
my $string = "Hello"; # String
my $undef = undef; # Undefined value
Arrays
perl
12345my @fruits = ("apple", "banana", "cherry");
print $fruits[0]; # Accessing first element
push @fruits, "date"; # Add to end
pop @fruits; # Remove last element
Hashes (Associative Arrays)
perl
12345678my %person = (
"name" => "John",
"age" => 30,
"city" => "New York"
);
print $person{"name"}; # Accessing hash value
$person{"country"} = "USA"; # Adding new key-value pair
References
perl
123456789my $scalar_ref = \42; # Scalar reference
my $array_ref = ["a", "b", "c"]; # Array reference
my $hash_ref = {"key" => "value"}; # Hash reference
# Dereferencing
print $$scalar_ref;
print $array_ref->[1];
print $hash_ref->{"key"};
Variables and Constants
perl
123456789my $local_var = "local"; # Lexically scoped variable
our $global_var = "global"; # Package-level variable
constant PI => 3.14159; # Constant definition
# Special variables
$_ = "default variable"; # Default input/pattern-searching space
@ARGV; # Command-line arguments
%ENV; # Environment variables
Operators
Arithmetic Operators
perl
1234567my $sum = 5 + 3; # Addition
my $diff = 10 - 4; # Subtraction
my $prod = 6 * 7; # Multiplication
my $div = 15 / 3; # Division
my $mod = 10 % 3; # Modulo
my $pow = 2 ** 3; # Exponentiation
Comparison Operators
perl
1234567891011# Numeric comparisons
if (5 == 5) { } # Equal
if (10 != 5) { } # Not equal
if (10 > 5) { } # Greater than
if (5 <= 10) { } # Less than or equal
# String comparisons
if ("abc" eq "abc") { } # String equal
if ("abc" ne "def") { } # String not equal
if ("abc" lt "def") { } # Less than (lexically)
Logical Operators
perl
1234if ($a && $b) { } # Logical AND
if ($a || $b) { } # Logical OR
if (!$condition) { } # Logical NOT
Regex Operators
perl
12345if ($string =~ /pattern/) { # Match regex
# Do something
}
$string =~ s/old/new/g; # Global substitution
Control Structures
Conditional Statements
perl
1234567891011if ($condition) {
# Code block
} elsif ($another_condition) {
# Alternative block
} else {
# Default block
}
# Ternary operator
my $result = $condition ? $true_value : $false_value;
Loops
perl
123456789101112131415161718192021# For loop
for (my $i = 0; $i < 10; $i++) {
print $i;
}
# Foreach loop
my @array = (1, 2, 3, 4, 5);
foreach my $item (@array) {
print $item;
}
# While loop
while ($condition) {
# Code block
}
# Do-while loop
do {
# Code block
} while ($condition);
Switch-like Functionality (Perl 5.10+)
perl
1234567use feature 'switch';
given ($variable) {
when ('value1') { /* code */ }
when ('value2') { /* code */ }
default { /* code */ }
}
Functions (Subroutines)
perl
123456789101112131415161718192021# Simple subroutine
sub greet {
my $name = shift;
return "Hello, $name!";
}
# Subroutine with multiple parameters
sub calculate {
my ($a, $b, $operation) = @_;
given ($operation) {
when ('add') { return $a + $b; }
when ('subtract') { return $a - $b; }
}
}
# Anonymous subroutine (function reference)
my $multiply = sub {
my ($a, $b) = @_;
return $a * $b;
};
Object-Oriented Programming
perl
12345678910111213141516171819202122232425262728293031# Class definition
package Person;
use strict;
use warnings;
sub new {
my ($class, $name, $age) = @_;
my $self = {
name => $name,
age => $age
};
bless $self, $class;
return $self;
}
sub introduce {
my ($self) = @_;
return "I'm " . $self->{name};
}
# Inheritance
package Employee;
use parent 'Person';
sub new {
my ($class, $name, $age, $job) = @_;
my $self = $class->SUPER::new($name, $age);
$self->{job} = $job;
return $self;
}
Error Handling
perl
123456789101112131415# Die (terminate program)
die "Fatal error message" if $error_condition;
# Warn (print warning)
warn "Warning message" if $warning_condition;
# Exception handling with eval
eval {
# Risky code
die "Something went wrong";
};
if ($@) {
print "Caught error: $@";
}
File I/O
perl
12345678910111213141516# Reading from a file
open(my $fh, '<', 'filename.txt') or die "Can't open file: $!";
while (my $line = <$fh>) {
chomp $line;
print $line;
}
close $fh;
# Writing to a file
open(my $out, '>', 'output.txt') or die "Can't open file: $!";
print $out "Some text\n";
close $out;
# Appending to a file
open(my $append, '>>', 'log.txt') or die "Can't open file: $!";
Common Libraries and Frameworks
- CPAN (Comprehensive Perl Archive Network)
- Module installation:
cpan Module::Name
- Module installation:
- Standard library modules:
File::Path- File and directory operationsLWP::Simple- Web interactionsJSON- JSON processingDBI- Database interactions
Best Practices
- Use
use strict;anduse warnings;in all scripts - Use meaningful variable names
- Prefer lexical variables with
my - Use references for complex data structures
- Leverage CPAN for existing solutions
- Write modular, reusable code
- Use
perldocfor documentation
Testing
perl
123456789101112use Test::More;
sub add {
my ($a, $b) = @_;
return $a + $b;
}
# Test cases
is(add(2, 3), 5, "Addition works");
isnt(add(2, 2), 5, "Not equal test");
done_testing();
Resources for Further Learning
- Official Documentation: https://www.perl.org/docs.html
- Books:
- "Learning Perl" by Randal L. Schwartz
- "Intermediate Perl" by Randal L. Schwartz
- Online Resources:
- perldoc.perl.org
- metacpan.org
- perlmonks.org
Continue Learning
Discover more cheatsheets to boost your productivity