# For loop
for (my $i = 0; $i < 5; $i++) {
print "$i ";
}
# Foreach loop
my @fruits = ("apple", "banana", "cherry");
foreach my $fruit (@fruits) {
print "$fruit\n";
}
# While loop
my $count = 0;
while ($count < 5) {
print "$count ";
$count++;
}
# Until loop (opposite of while)
my $n = 0;
until ($n >= 5) {
print "$n ";
$n++;
}
# Loop control
foreach my $num (1..10) {
last if $num > 5; # Exit loop
next if $num % 2 == 0; # Skip to next iteration
print "$num ";
}
Subroutines
Example:
# Basic subroutine
sub greet {
my ($name) = @_;
print "Hello, $name!\n";
}
greet("Alice");
# Multiple parameters
sub add {
my ($a, $b) = @_;
return $a + $b;
}
my $sum = add(5, 3);
# Default parameters (using // operator)
sub greet_with_title {
my ($name, $title) = @_;
$title //= "Mr./Ms."; # Default value
print "$title $name\n";
}
# Return multiple values
sub get_stats {
my @numbers = @_;
my $sum = 0;
$sum += $_ for @numbers;
my $count = scalar @numbers;
my $avg = $sum / $count;
return ($sum, $avg);
}
my ($total, $average) = get_stats(1, 2, 3, 4, 5);
Arrays
Example:
my @array = (1, 2, 3, 4, 5);
# Array operations
push @array, 6; # Add to end
my $last = pop @array; # Remove from end
unshift @array, 0; # Add to beginning
my $first = shift @array; # Remove from beginning
# Array slicing
my @slice = @array[1..3];
# Array length
my $length = scalar @array;
my $last_index = $#array;
# Iterate with index
for my $i (0..$#array) {
print "$i: $array[$i]\n";
}
# Join and split
my $str = join(", ", @array);
my @words = split(/\s+/, "hello world from perl");
Hashes
Example:
my %hash = (
name => "Alice",
age => 30,
city => "London"
);
# Access values
my $name = $hash{name};
# Add/modify entries
$hash{country} = "UK";
$hash{age} = 31;
# Delete entries
delete $hash{city};
# Check if key exists
if (exists $hash{name}) {
print "Name exists\n";
}
# Iterate over hash
foreach my $key (keys %hash) {
my $value = $hash{$key};
print "$key: $value\n";
}
# Hash slicing
my @values = @hash{qw(name age)};
Regular Expressions
Example:
my $text = "The quick brown fox";
# Matching
if ($text =~ /quick/) {
print "Found 'quick'\n";
}
# Case-insensitive matching
if ($text =~ /QUICK/i) {
print "Found 'quick' (case-insensitive)\n";
}
# Substitution
$text =~ s/brown/red/; # Replace first occurrence
$text =~ s/fox/dog/g; # Replace all occurrences
# Capture groups
if ($text =~ /(\w+) (\w+)/) {
print "First word: $1\n";
print "Second word: $2\n";
}
# Split with regex
my @words = split(/\s+/, $text);
# Match operator variations
my $count = ($text =~ tr/a-z/A-Z/); # Transliterate
File I/O
Example:
# Open file for reading
open my $fh, "<", "input.txt" or die "Cannot open: $!";
while (my $line = <$fh>) {
chomp $line; # Remove newline
print "$line\n";
}
close $fh;
# Open file for writing
open my $out, ">", "output.txt" or die "Cannot write: $!";
print $out "Hello, file!\n";
close $out;
# Open file for appending
open my $append, ">>", "log.txt" or die "Cannot append: $!";
print $append "Log entry\n";
close $append;
# Read entire file
open my $fh2, "<", "file.txt" or die $!;
my @lines = <$fh2>;
close $fh2;
# One-liner file reading
my @content = do {
open my $f, "<", "file.txt" or die $!;
<$f>;
};
References
Example:
# Array reference
my @array = (1, 2, 3);
my $arrayref = \@array;
print $arrayref->[0]; # Access element
print @{$arrayref}; # Dereference
# Hash reference
my %hash = (a => 1, b => 2);
my $hashref = \%hash;
print $hashref->{a}; # Access value
print %{$hashref}; # Dereference
# Anonymous array
my $anonarray = [1, 2, 3];
# Anonymous hash
my $anonhash = {a => 1, b => 2};
# Reference to subroutine
my $subref = \&greet;
$subref->("Alice"); # Call through reference
Object-Oriented Programming
Example:
package Person;
sub new {
my ($class, %args) = @_;
my $self = {
name => $args{name},
age => $args{age}
};
return bless $self, $class;
}
sub get_name {
my ($self) = @_;
return $self->{name};
}
sub set_age {
my ($self, $age) = @_;
$self->{age} = $age;
}
sub greet {
my ($self) = @_;
print "Hello, I'm ", $self->{name}, "\n";
}
package main;
my $person = Person->new(name => "Alice", age => 30);
$person->greet();
$person->set_age(31);
Map and Grep
Example:
my @numbers = (1, 2, 3, 4, 5);
# Map: transform each element
my @doubled = map { $_ * 2 } @numbers;
my @squared = map { $_ ** 2 } @numbers;
# Grep: filter elements
my @evens = grep { $_ % 2 == 0 } @numbers;
my @large = grep { $_ > 3 } @numbers;
# Combine map and grep
my @result = map { $_ * 10 }
grep { $_ % 2 == 0 }
(1..10);
Error Handling
Example:
# Die for fatal errors
die "Fatal error!" unless $condition;
die "Cannot open file: $!" unless open my $fh, "<", "file.txt";
# Warn for non-fatal warnings
warn "This is a warning\n" if $debug;
# Eval for exception handling
eval {
# Code that might die
die "Something went wrong";
};
if ($@) {
print "Caught error: $@\n";
}
# Try-catch pattern
eval {
risky_operation();
1; # Return true if successful
} or do {
my $error = $@;
handle_error($error);
};
Special Operators
Example:
# Spaceship operator (three-way comparison)
my $cmp = $a <=> $b; # Returns -1, 0, or 1
# String comparison
my $strcmp = $str1 cmp $str2;
# String concatenation
my $full = $first . " " . $last;
# String repetition
my $line = "-" x 40;
# Range operator
my @range = (1..10);
my @letters = ('a'..'z');
# Fat comma (auto-quotes left side)
my %hash = (
name => "Alice",
age => 30
);
# Defined-or operator
my $value = $input // "default";
# Smart match (Perl 5.10+)
if ($value ~~ @array) {
print "Value is in array\n";
}
Modules and Packages
Example:
package MyModule;
use strict;
use warnings;
# Export functionality
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(function1 function2);
sub function1 {
print "Function 1\n";
}
sub function2 {
print "Function 2\n";
}
1; # Module must return true
package main;
use MyModule;
function1();
Built-in Functions
Example:
# String functions
my $upper = uc("hello"); # Uppercase
my $lower = lc("HELLO"); # Lowercase
my $len = length("hello"); # String length
my $sub = substr("hello", 1, 3); # Substring
my $idx = index("hello", "ll"); # Find substring
my $rev = reverse("hello"); # Reverse string
# Array functions
my @sorted = sort @array;
my @reversed = reverse @array;
my $joined = join(",", @array);
# Math functions
my $abs = abs(-5);
my $sqrt = sqrt(16);
my $int = int(3.7);
my $rand = rand(10); # Random 0 to 10
my $sin = sin(3.14159);
# Type checking
my $isdef = defined $var;
my $exists = exists $hash{key};
my $type = ref $var; # Returns type of reference