Perl Cheatsheet



The Perl Cheatsheet provides a quick reference to all the fundamental topics. This open-source language performs various tasks such as text processing, web development, networking, and system administration. By learning this cheat sheet, you can get the basic concept for interview preparation. Go through this cheat sheet and learn the Perl programming language.

1. Basic Overview of Perl

In the basic overview of Perl, we learn the basic syntax to display the text in the output.

print "Tutorialspoint!\n";

2. Comments

Comments are used to display the text information. In Perl, there are two ways to define comments −

  • Single line comment − This is denoted using #.
  • Multi-line comment − This is denoted by =begin =end.

Below is the implementation of comments in Perl −

# This is single line comment.

=begin 
This is a multi-line comment.
=cut

3. Data Types

In Perl, data types are used to classify the data based on given values.

use strict;
use warnings;
use Scalar::Util 'reftype';

# Defining different types of data
my $scalar = "Tutorialspoint!";
my @array = (1, 2, 3, 4);
my %hash = ('name' => 'Ramesh', 'age' => 40);
my $array_ref = \@array;  
my $hash_ref = \%hash;   

# Function to check and print the type of data
sub check_data_type {
    my ($data) = @_;
    
    if (!defined $data) {
        print "Data is undefined.\n";
    } elsif (ref($data) eq 'ARRAY') {
        print "Data is an array reference.\n";
    } elsif (ref($data) eq 'HASH') {
        print "Data is a hash reference.\n";
    } elsif (ref($data) eq '') {
        print "Data is a scalar: $data\n";
    } else {
        print "Data is of unknown type.\n";
    }
}
# Check types of different data
print "Checking types of different data:\n";
check_data_type($scalar);      
check_data_type(\@array);      
check_data_type(\%hash);       
check_data_type($array_ref);   
check_data_type($hash_ref);    
check_data_type(undef);        

4. Variables

Perl variables are reserved memory location that can be used to store the values. There are three types of variables −

  • Scalar: This represents the single values and is denoted by the dollar sign '$'.
  • arrays: This holds an ordered list of scalars and is denoted by '@'.
  • hashes: This stores the key-value pairs and is denoted by the percentage sign '%'.

Below is the implementation of the above variables of Perl −

# Scalar variables
$scalar = "Hello, World!";
$number = 42;

# arrays variables
@array = (1, 2, 3, 4);

# hashes variables
%hash = ("key1", "value1", "key2", "value2");

5. Special Variables

The special variables are the variables that use punctuation characters after the usual variable indicator ($, @, or %) like $_. Below is the implementation of the program −

foreach ('JAVA', 'Python', 'Perl') 
{ 
   print($_); 
   print("\n"); 
} 

6. Format

In Perl, a format defines how output is structured.

format FormatName =
fieldline
value_1, value_2, value_3
fieldline
value_1, value_2, value_3

The explanation of above format syntax in perl −

  • Format Name: This is denoted by FormatName.
  • Field Line: This specifies how to format data. This contains text and field holders.
  • Value Lines: This describe the values to be entered into the field lines.
  • End of Format: This is marked by single period (.).
  • Field Holders: This reserved spaces for data to be entered later.

7. Decision Making Statement

In Perl, a decision making statement is a control structure that allows programmer to make choice based on specific condition.

i. if Statement

This if statement implement the block of code if the specified condition is true.

my $num = 10;
if ($num > 5) {
    print "Number is greater than 5\n";
}

ii. if-else Statement

The if-else statement implements the block of code; if the condition is true, it will execute; otherwise, it will be false.

my $number = 3;
if ($number > 5) {
    print "Number is greater than 5\n";
} else {
    print "Number is 5 or less\n";
}

iii. if-elsif ladder

The if-elsif ladder in Perl is a control structure used to execute different blocks of code based on multiple conditions. It consists of an if statement followed by one or more elsif statements.

my $num = 5;
if ($num > 5) {
    print "Number is greater than 5\n";
} elsif ($num == 5) {
    print "Number is equal to 5\n";
} else {
    print "Number is less than 5\n";
}

iv. nested if Statement

This is nested if statement inside another if statement that allows multiple levels of conditions.

my $num = 10;
if ($num > 5) {
    print "Number is greater than 5\n";
    if ($num > 8) {
        print "Number is also greater than 8\n";
    }
}

v. unless statement

In the unless statement, if the condition is false the statement will executes.

my $num = 3;
unless ($num > 5) {
    print "Number is 5 or less\n";
}

vi. unless-else statement

The unless−else statement implements the block of code if the specified condition is false. This is the opposite of an if-statement.

my $num = 7;
unless ($num > 5) {
    print "Number is 5 or less\n";
} else {
    print "Number is greater than 5\n";
}

vii. unless-elsif statement

The unless−elsif statement implements the block of code; if the specified condition is false, it passes to the other block to check the true condition.

my $num = 5;
unless ($num > 5) {
    print "Number is 5 or less\n";
} elsif ($num == 5) {
    print "Number is equal to 5\n";
} else {
    print "Number is greater than 5\n";
}

viii. Switch Statement

The switch statement allows user to execute different blocks of code based on the value of a variable or expression. It is useful for handling multiple conditions without using multiple if-else statements.

use strict;
use warnings;

my $day = 'Wednesday';

if ($day eq 'Monday') {
    print "Start of the work week.\n";
} elsif ($day eq 'Wednesday') {
    print "Midweek day.\n";
} elsif ($day eq 'Friday') {
    print "End of the work week.\n";
} elsif ($day eq 'Saturday' || $day eq 'Sunday') {
    print "Weekend!\n";
} else {
    print "Not a valid day.\n";
}

8. Loops

Loops are the set of instructions that continuously repeat until the specific condition is met.

i. while loop

The while loop repeats the statement where the condition is true, and the condition is checked before the loop block.

my $cnt = 0;
while ($cnt < 5) {
    print "$cnt\n";
    $cnt++;
}

ii. until loop

The until loop repeats the statement where the condition is true, and the condition is checked before the loop block.

my $cnt = 0;
until ($cnt == 5) {
    print "$cnt\n";
    $cnt++;
}

iii. for loop

The for loop block executes the statement multiple times in support of the loop variable.

for (my $i = 0; $i < 5; $i++) {
    print "$i\n";
}

iv. foreach loop

The foreach loop iterates over the list and assigns each element to the variable.

my @list = (1, 2, 3, 4, 5);
foreach my $i (@list) {
    print "$i\n";
}

v. do...while loop

The do...while loop is similar to the while loop but the condition is checked after executing the loop block.

my $cnt = 0;
do {
    print "$cnt\n";
    $cnt++;
} while ($cnt < 5);

9. Arrays

In Perl, an array variable holds an ordered list of scalar values. The array variables are represented using the '@' sign.

@ages = (55, 18, 64);             
@names = ("Faran", "Ravi", "Teja");

print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";

10. Strings

In Perl, strings are represented using single quotes or double quotes.

$str1 = 'Tutorialspoint!'
$str2 = "Welcome to Tutorialspoint!"

11. Scalar

In Perl, a scalar is a fundamental data type that stores a single value. The values can be a string, number, or the reference of another data type. This is denoted by '$'.

$int_num = 45; # integer 
$str_name = "Tutorialspoint"; # string 
$float_num = 1445.50; # float

print "Integer = $int_num\n";
print "String = $str_name\n";
print "Float = $float_num\n";

12. Hashes

The hashes are defined using key-value pairs where each key is unique.

use strict;
use warnings;

# Define a hash with student names as keys and their scores as values
my %students = (
    'Prabhjot Singh' => 85,
    'Ritik'   => 90,
    'Ayush Chanderi' => 78,
);

# Extracting keys from the hash
my @key_array = keys %students;
print "Student names are:\n";
foreach my $student (@key_array) {
    print "$student: $students{$student}\n";  
}

13. Operators

In Perl, an operator is the symbol that performs a specific operation based on one or more operands.

Operators Description Example
Arithmetic Operators Basic mathematical operations. '$a + $b', '$a - $b', '$a * $b', '$a / $b', '$a % $b'
Equality Operators Compares two values for equality. '$a == $b', '$a != $b', '$a <=> $b'
Logical Operators Combine conditional statements. '$a && $b', '$a || $b', '!$a'
Assignment Operators Assign values to variables. '$a = $b', '$a += $b', '$a -= $b', '$a *= $b', '$a /= $b', '$a %= $b'
Bitwise Operators Perform operations at the bit level. '$a & $b', '$a | $b', '$a ^ $b', '~$a', '$a << $b', '$a >> $b'
Quote-like Operators Used for quoting strings and interpolating variables. 'q//', 'qq//', 'qx//', 'qw//'
Miscellaneous Operators Includes various operators like the defined operator and the range operator. 'defined($var)', '1..5'

14. Date and Time

To get the current date and time in Perl, use localtime() that shows the current date and time.

$datetime = localtime();   
print "Local Time of the System : $datetime\n";  

15. Subroutines

In Perl, subroutines are defined using groups of statements, which can be called multiple times within the program. This is denoted by the keyword sub.

sub subroutine_name {
   body of the subroutine
}

16. File I/O

In Perl, file Input/Output (I/O) defines the process of reading from and writing in the files.

# Writing to a file
open(my $fh, '>', 'example_file.txt') or die "File cannot be open: $!";
print $fh "Tutorialspoint!\n";
close($fh);

# Reading from a file
open(my $fh, '<', 'example_file.txt') or die "File cannot be open: $!";
while (my $line = <$fh>) {
    print $line;
}
close($fh);

17. Error Handling

In Perl, error handling is the way to detect errors during program execution. It provides two built-in functions to get the exception and warning −

  • die(): This is used to terminate the program immediately.
  • warn(): This prints the warning message to the standard error stream.

Following the below code shows the syntax to write the program for error handling in Perl −

# syntax of die()
open FILE, "filename.txt" or die "Cannot open file: $!\n";
# syntax of warn()
open FILE, "filename.txt" or warn "Cannot open file: $!\n";

18. Regex Expression

In Perl, a regular expression is a pattern that used to match character combinations in strings.

$x = "Tutorialspoint"; 
# if match found
if ($x =~ m[Tutor])  
{ 
   print "Match Found\n"; 
} 
# if the match is not found
else 
{ 
   print "Match Not Found\n"; 
} 
Advertisements