Perl Cheatsheet
1. Variables and Data Types
$age = 30; # Scalar
$name = "John"; # String
@numbers = (1, 2, 3); # Array
%person = ('name' => 'John', 'age' => 30); # Hash
# Contexts
my @array = (1, 2, 3);
my $count = @array; # Scalar context returns length
# Arrays and Hashes
my @fruits = ('apple', 'banana', 'orange');
my %person = ( 'name' => 'John', 'age' => 30 );
2. Control Flow (Conditionals, Loops)
# If-else
if ($age > 18) {
print "Adult";
} else {
print "Minor";
}
# Loops
for my $i (1..5) {
print "$i\n";
}
my $i = 0;
while ($i < 5) {
print "$i\n";
$i++;
}
# Unless (reverse if)
unless ($age > 18) {
print "Minor";
}
3. Functions and Subroutines
sub greet {
my ($name) = @_;
return "Hello, $name";
}
print greet("John"); # Output: Hello, John
# Subroutine with multiple return values
sub calculate {
my ($a, $b) = @_;
return ($a + $b, $a * $b);
}
my ($sum, $product) = calculate(5, 10);
print "$sum, $product"; # Output: 15, 50
4. Regular Expressions
# Match operator
if ($text =~ /pattern/) {
print "Match found";
}
# Substitute operator
$text =~ s/foo/bar/g;
# Capture groups
if ($text =~ /(\d+)/(\w+)/) {
print "$1, $2";
}
5. File Handling
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";
while (my $line = <$fh>) {
print $line;
}
close($fh);
# Writing to a file
open(my $out, '>', 'output.txt') or die "Cannot open file: $!";
print $out "Hello, Perl!";
close($out);
6. References
# Scalar reference
my $x = 10;
my $ref_x = \$x;
print $$ref_x; # Dereference scalar reference
# Array reference
my @arr = (1, 2, 3);
my $arr_ref = \@arr;
print @{$arr_ref}; # Dereference array reference
# Hash reference
my %hash = ('a' => 1, 'b' => 2);
my $hash_ref = \%hash;
print %{$hash_ref};
7. Modules and Packages
# Loading a module
use Math::Trig;
print tan(1);
# Custom package
package MyPackage;
sub hello {
print "Hello from MyPackage!";
}
# Use in script
use MyPackage;
MyPackage::hello();
8. Object-Oriented Programming
package Animal;
sub new {
my $class = shift;
my $self = { 'name' => shift };
bless $self, $class;
return $self;
}
sub speak {
my $self = shift;
print "$self->{name} makes a sound";
}
package Dog;
use parent 'Animal';
sub speak {
my $self = shift;
print "$self->{name} barks";
}
# Creating objects
my $dog = Dog->new("Rex");
$dog->speak(); # Output: Rex barks
9. Error Handling
# Using eval for error handling
eval {
die "Something went wrong";
};
if ($@) {
print "Error: $@";
}
# Raising exceptions
die "Fatal error!";
10. References and Data Structures
# Nested data structures
my $person = {
'name' => 'John',
'age' => 30,
'address' => {
'city' => 'New York',
'zip' => '10001'
}
};
print $person->{'name'}; # John
print $person->{'address'}->{'city'}; # New York
11. Signals and IPC
# Signal handling
$SIG{'INT'} = sub {
print "Caught SIGINT!\n";
exit;
};
while (1) {
print "Running...\n";
sleep(1);
}
12. Command Line Arguments
my $arg1 = $ARGV[0];
my $arg2 = $ARGV[1];
print "Argument 1: $arg1, Argument 2: $arg2\n";
# Iterating over command line args
foreach my $arg (@ARGV) {
print "Arg: $arg\n";
}
13. Hashes and Sorting
# Sorting hash keys
my %person = ('name' => 'John', 'age' => 30);
foreach my $key (sort keys %person) {
print "$key: $person{$key}\n";
}
# Sorting arrays
my @numbers = (5, 2, 9, 1);
my @sorted = sort { $a <=> $b } @numbers;
print "Sorted: @sorted";
14. Multithreading with Perl
use threads;
sub task {
my $id = shift;
print "Thread $id running\n";
}
# Create threads
my $t1 = threads->create('task', 1);
my $t2 = threads->create('task', 2);
# Join threads
$t1->join();
$t2->join();
15. Context Sensitivity
# Scalar context
my @arr = (1, 2, 3);
my $count = @arr; # Returns number of elements
print "$count\n"; # Output: 3
# List context
my ($first, $second) = @arr;
print "$first, $second\n"; # Output: 1, 2