Skip to content

2. Perl

1. Getting Started

To get started with Perl on Ubuntu, follow these steps:

1.1 Check if Perl is Installed

Perl comes pre-installed on most Ubuntu systems. You can check if it’s already installed by running:

Terminal window
perl -v

This should display the version of Perl installed on your system. If Perl is not installed, proceed to the next step.

1.2 Install Perl (if needed)

If Perl is not already installed, you can install it using the following command:

Terminal window
sudo apt update
sudo apt install perl

This installs the latest stable version of Perl available through the Ubuntu repositories.

1.3 Install Perl Modules (Optional)

Many Perl scripts rely on additional modules from CPAN (Comprehensive Perl Archive Network). To install Perl modules, you can use the cpan tool. For example, to install a module like LWP::UserAgent, you can run:

Terminal window
sudo cpan LWP::UserAgent

Alternatively, you can install modules using cpanm, which is a more modern and convenient tool. First, install cpanminus:

Terminal window
sudo apt install cpanminus

Then, use it to install any Perl module:

Terminal window
sudo cpanm LWP::UserAgent

1.4 Write Your First Perl Script

Create a simple Perl script to test your setup. Open a text editor (like nano) and write the following code in a file called hello.pl:

Terminal window
nano hello.pl

Add this Perl code to the file:

#!/usr/bin/perl
use strict;
use warnings;
print "Hello, World!\n";

1.5 Make the Script Executable

To run the Perl script from the command line, you can make the file executable:

Terminal window
chmod +x hello.pl

1.6 Run Your Perl Script

Now, you can execute the script by running:

Terminal window
./hello.pl

You should see Hello, World! printed on your terminal.

1.7 Explore Perl Documentation

Perl comes with excellent built-in documentation. To learn more about a particular topic or function, you can use the perldoc command. For example, to learn about the print function:

Terminal window
perldoc -f print

Perl supports a variety of data structures and control structures, allowing flexibility in writing scripts. Here’s a detailed overview of both:


2. Data Structures in Perl

  1. Scalars

    • A scalar represents a single value, which could be a number, a string, or a reference.
    • Scalars are prefixed with a $.
    • Example:
      my $number = 42;
      my $string = "Hello, Perl!";
  2. Arrays

    • Arrays hold ordered lists of scalars.
    • They are prefixed with an @ and indexed using square brackets [].
    • Example:
      my @fruits = ("apple", "banana", "cherry");
      print $fruits[0]; # Outputs "apple"
  3. Hashes

    • Hashes (associative arrays) store key-value pairs.
    • They are prefixed with a % and are accessed using curly braces {}.
    • Example:
      my %ages = ("John" => 25, "Jane" => 28, "Doe" => 22);
      print $ages{"John"}; # Outputs 25
  4. References

    • A reference is a scalar that points to another data structure (like arrays, hashes, or subroutines).
    • To create a reference, use the backslash (\) operator, and to dereference, use the appropriate sigil ($, @, %).
    • Example:
      my @numbers = (1, 2, 3);
      my $array_ref = \@numbers; # Reference to @numbers
      print $array_ref->[0]; # Outputs 1
  5. Complex Data Structures

    • You can create more complex structures like arrays of arrays or hashes of arrays using references.
    • Example of an array of arrays:
      my @matrix = ([1, 2, 3], [4, 5, 6], [7, 8, 9]);
      print $matrix[0][1]; # Outputs 2

3. Control Structures in Perl

  1. Conditional Statements

    • if, elsif, else: The basic conditional statement.

      if ($age > 18) {
      print "Adult";
      } elsif ($age == 18) {
      print "Just turned adult";
      } else {
      print "Minor";
      }
    • Ternary Operator (?:): A shorthand conditional expression.

      my $status = ($age >= 18) ? "Adult" : "Minor";
  2. Loops

    • while: Loops while a condition is true.

      my $i = 0;
      while ($i < 5) {
      print "$i\n";
      $i++;
      }
    • for: The typical for loop as in other languages.

      for (my $i = 0; $i < 5; $i++) {
      print "$i\n";
      }
    • foreach: Iterates over a list or array.

      my @colors = ("red", "green", "blue");
      foreach my $color (@colors) {
      print "$color\n";
      }
    • until: Loops until a condition is true (opposite of while).

      my $i = 0;
      until ($i == 5) {
      print "$i\n";
      $i++;
      }
  3. Loop Control

    • next: Skip to the next iteration.

      for (my $i = 0; $i < 10; $i++) {
      next if $i == 5; # Skip iteration when $i equals 5
      print "$i\n";
      }
    • last: Exit the loop immediately (similar to break in other languages).

      for (my $i = 0; $i < 10; $i++) {
      last if $i == 5; # Exit loop when $i equals 5
      print "$i\n";
      }
    • redo: Restarts the current iteration without checking the loop condition.

      my $i = 0;
      while ($i < 5) {
      print "$i\n";
      $i++;
      redo if $i == 3; # Repeats iteration for $i == 3
      }
  4. Switch-Like Statement (given/when)

    • Perl doesn’t have a native switch statement like some languages, but as of Perl 5.10, given/when provides similar functionality.
    use feature 'switch';
    my $value = 2;
    given ($value) {
    when (1) { print "One\n"; }
    when (2) { print "Two\n"; }
    default { print "Other\n"; }
    }
  5. Logical Operators

    • Logical AND (&&):

      if ($age > 18 && $country eq "USA") {
      print "Eligible";
      }
    • Logical OR (||):

      if ($age < 18 || $country ne "USA") {
      print "Not Eligible";
      }
    • Logical NOT (!):

      if (!defined($value)) {
      print "Value is undefined";
      }
  6. Error Handling (eval)

    • The eval function can be used for error trapping, acting somewhat like a try block in other languages.
    eval {
    # risky code here
    die "Error!" if $something_bad_happens;
    };
    if ($@) {
    print "An error occurred: $@";
    }