COURSE ยท 7 LESSONS ยท 100% FREE
๐Ÿช

Perl Programming

The duct tape of the Internet. Text processing powerhouse. Regex royalty. System admin's best friend.

0Lessons
0Code Examples
ZeroPrerequisites
0%
You've completed 0 of 7 lessons
J/โ†“ Next
K/โ†‘ Prev
Esc Collapse
/ Search
Foundations
01

Hello World & Setup

use strict; use warnings; are mandatory. print for output. $ for scalars, @ for arrays, % for hashes.

#!/usr/bin/perl
use strict;
use warnings;

print "Hello, World!\n";

my $name = "Mayank";
my $age = 15;
print "$name is $age\n";

# Run: perl file.pl
# Or: chmod +x file.pl && ./file.pl
02

Variables & Types

$scalar, @array, %hash. my for local scope. undef for undefined.

#!/usr/bin/perl
use strict; use warnings;

# Scalars
my $name = "Mayank";
my $age = 15;
my $pi = 3.14;
my $flag = 1;  # true

# Arrays
my @langs = ('Python', 'Perl', 'Go', 'Rust');
print $langs[0];  # Python
print scalar @langs;  # 4
push @langs, 'Java';
pop @langs;

# Hashes
my %person = (name => 'Mayank', age => 15);
print $person{name};
$person{email} = 'test@test.com';
delete $person{email};

# Dereferencing
my $aref = \@langs;
my $href = \%person;
print $$aref[0];
print $$href{name};
03

Control Flow

if/elsif/else/unless. for/foreach. while/until. Labels for nested loops.

#!/usr/bin/perl
use strict; use warnings;

my $score = 85;
if ($score >= 90) { print "A\n"; }
elsif ($score >= 80) { print "B\n"; }
else { print "C\n"; }

# Unless (opposite of if)
unless ($score < 50) { print "Passed\n"; }

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

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

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

Subroutines

sub keyword. Pass arrays by reference. Return values. Named params via hash.

#!/usr/bin/perl
use strict; use warnings;

sub add {
    my ($a, $b) = @_;
    return $a + $b;
}

sub greet {
    my %args = @_;
    my $name = $args{name} // 'World';
    my $prefix = $args{prefix} // 'Hello';
    return "$prefix, $name!";
}

sub sum {
    my @nums = @_;
    my $total = 0;
    $total += $_ for @nums;
    return $total;
}

print add(3, 4), "\n";
print greet(name => 'Mayank'), "\n";
print greet(name => 'World', prefix => 'Hi'), "\n";
print sum(1, 2, 3, 4, 5), "\n";
Text & Data
05

Regex (Regular Expressions)

Perl's crown jewel. m//, s///, tr///. Match, substitute, transliterate.

#!/usr/bin/perl
use strict; use warnings;

my $text = "Hello World 123";

# Match
if ($text =~ /World/) { print "Found World\n"; }
if ($text =~ /\d+/) { print "Has numbers: $&\n"; }

# Capture groups
if ($text =~ /(\w+) (\w+)/) {
    print "Word 1: $1, Word 2: $2\n";
}

# Substitute
my $s = $text;
$s =~ s/World/Perl/;
print "$s\n";  # Hello Perl 123

# Global replace
$s =~ s/\b\w+\b/uc($&)/ge;
print "$s\n";  # HELLO PERL 123

# Transliterate
my $abc = "hello";
$abc =~ tr/a-z/A-Z/;
print "$abc\n";  # HELLO

# Named captures
if ($text =~ /(?<word>\w+) (?<word2>\w+)/) {
    print "$+{word} $+{word2}\n";
}
06

File I/O

open, close, <>, readline. Slurp mode. Diamond operator for files/STDIN.

#!/usr/bin/perl
use strict; use warnings;

# Write
open my $fh, '>', 'test.txt' or die $!;
print $fh "Hello Perl!\n";
print $fh "Line 2\n";
close $fh;

# Read line by line
open my $in, '<', 'test.txt' or die $!;
while (my $line = <$in>) {
    print $line;
}
close $in;

# Slurp entire file
open my $slurp, '<', 'test.txt';
my $content = do { local $/; <$slurp> };
close $slurp;
print $content;

# Append
open my $log, '>>', 'log.txt';
print $log scalar(localtime) . " event\n";
close $log;

# Read CSV
open my $csv, '<', 'data.csv';
while (<$csv>) {
    chomp;
    my @fields = split /,/;
    print join('\t', @fields), "\n";
}
07

References & Data Structures

References create complex data. Array of hashes, hash of arrays, nested structures.

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

# Array of hashes
my @users = (
    {name => 'Mayank', age => 15},
    {name => 'Alice', age => 20},
    {name => 'Bob', age => 12},
);

for my $u (@users) {
    print "$u->{name}: $u->{age}\n";
}

# Hash of arrays
my %groups = (
    admins => ['root', 'admin'],
    users => ['alice', 'bob', 'charlie'],
);

print Dumper(\%groups);

# Nested
my $tree = {
    left => { value => 1 },
    right => { value => 2, children => [] },
};
print $tree->{left}{value}, "\n";

# References to subroutines
my @callbacks = (
    sub { print "Hello\n" },
    sub { print "World\n" },
);
$_->() for @callbacks;