Resources for Perl

by Fredrik Daneby

Useful links

perl.org[ https://www.perl.org ]
Perl documentation[ https://perldoc.perl.org ]
perl.com[ https://www.perl.com ]
PerlMonks[ https://www.perlmonks.org ]
Perl Maven[ https://perlmaven.com/ ]

Snippets

Basics

Data types

#!bin/perl
		
## Scalar variables ($)
my $scalar  = 1;
printf("\$scalar is $scalar\n");

# Float
$scalar = 2.01;
printf("\$scalar is $scalar\n");

# String
$scalar = "string";
printf("\$scalar is $scalar\n");

# Reference
my $number = 100;
$scalar = \$number;
printf("\$scalar is $scalar and holds a reference to a scalar with value $$scalar\n");


## Arrays (@)
# Array of integers
my @array_2 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
printf("Array 2: " . join(" ", @array_2) . "\n");

my $value = $array_2[4];                            # Get value at index 
printf("Value at index 4 of \$array_2: $value\n");

$array_2[4] = 10;                                   # Set value at index
printf("Value at index 4 of \$array_2: $array_2[4]\n");

# Array of strings
@array_3 = ("one", "two", "three");
printf("Array_3: " . join(" ", @array_3) . "\n");


## Hashes (%)
%hash_1 = ("one" => 1, "two" => 2, "three" => 3);
$hash_1{"four"} = 4;
foreach my $key (keys(%hash_1)) {
    printf("Hash key is %s and has value %s\n", $key, $hash_1{$key});
}			

Variable scope - use strict

#!bin/perl

$variable = 10;

use strict;

# This will fail because we use strict rules

$another_variable = 20;

# This will not fail. Keyword "my" makes variable local to current scope
# This satisfies the strict rules

my $yet_another_variable = 30;


			

Namespace

#!bin/perl
use strict;
use warnings;

# Anonymous namespace within {}
my $value = 1;
{
    my $value = 0;
    print("Inside brackes: $value\n");
}
print("Outside brackets: $value\n");

package test;                  # Create a namespace "test"
our $value = 999;              # This generates a useful warning
print("Value is $value\n");
package main;                   
our $value = 111;
print("Value is $value\n");
			

Loops

#!bin/perl
use v5.10;
use strict;
use warnings;

say("Classic for-loop:");
for (my $i = 0; $i < 10; $i++) {
    print($i);
}

my $value = 1;
my @list = qw(a b c d);             		# qw( ) returns quoted words

say("\n\nFor loops over arrays:");
for my $item (@list) { print $item; }           # Iterate over array
for (@list) { print $_; }                       # Same thing but shorter
print for (@list);                              # Just because it's Perl

my @list2 = qw(e f g h);
say("\n\nForeach loops:");
foreach my $item2 (@list2) { print $item2; }
print foreach (@list2);

say("\n\nWhile loop: ");
while($value < 10) {
    print($value);
    ++$value;
}			

Subroutines

#!bin/perl

# Definition and declaration of a subroutine (function)

sub subroutine_1 {

    # Parameters are passed as a list in special array @_
    # Copy values to scalar variables in list context = ()
	
    my ($parameter_1, $parameter_2) = @_;
	
    print("subroutine_1 got $parameter_1 and $parameter_2\n");
}

# Call subroutine_1
subroutine_1(10, 20);

# Call subroutine_1 again with three parameters in an array (@)
# The array is flattened to a list of scalar values and only two are used.
my @array_of_parameters = (100, 200, 300);

subroutine_1(@array_of_parameters);

File I/O

Read whole file to string ("slurp")

#!bin/perl
use strict;
use warnings;

# File path is supplied at command line
my $file = shift;

open(my $fh, '<', $file) or die "Could not open input file $file\n";

# Enable slurp-mode and read file to string
my $data = '';
{
	local $/;
	$data = <$fh>;
	close $fh;
}			


Read whole file to an array of lines

#!bin/perl
use strict;
use warnings;

# File path is supplied at command line 
my $file = shift;

open(my $fh, '<', $file) or die "Could not open input file $file\n";

my @lines = <$fh>;

# One way to iterate over the lines
for(@lines) {
    print($_);
}

# Another way to iterate over the lines
for my $line (@lines) {
    print($line);
}	

close($fh);
			

Iterate over filehandle directly

#!bin/perl
use strict;
use warnings;

# File path is supplied at command line 
my $file = shift;

open(my $fh, '<', $file) or die "Could not open input file $file\n";

while(<$fh>) {
    print($_);
}

close($fh);
			

Write to a file

#!bin/perl
use strict;
use warnings;

# A module for working with paths in an OS independant manner
use File::Spec;                              

my $folder      = File::Spec->curdir();      # Returns current working dir.
my $filename    = "story.txt";
my $path        = File::Spec->join($folder, $filename);

open(my $fh, '>', $path) or die "Could not open output file $path\n";

my $story = "Once upon a time, there was a little story and it ended.\n";

print $fh $story;

close($fh);
			

String operations

String concatenation

#!bin/perl
use v5.10;
use strict;
use warnings;

# Variables in double-quoted strings are evaluated
my $short_string = "ABCD";
my $long_string = "$short_string are four letters";
say $long_string;

# The dot operator . enables string concatenation
my $longer_string = $long_string . ", that are part of the alphabet";
say $longer_string;

# The numeric operator + is NOT USEFUL with strings in Perl
my $firstname = "Elin";
my $lastname = "Johansson";
my $fullname = $firstname + $lastname;
say $fullname;
	
			

Count occurences of a character in a string

#!bin/perl
use strict;
use warnings;

# Count the number of '-' in string

my $string = "A-B-C-D-E-F";

# One way
my $count = 0;
$count = $string =~ tr/-//;             # Translate(no replacement = only count)
print($count . "\n");

# Another way
$count = 0;
++$count while $string =~ m/-/g;         # Match (m) globally (g)
print($count . "\n");

# A third way
$count = 0;
$count = () = $string =~ m/-/g;          # Match (m) globally (g)
print($count . "\n");

# A fourth way
$count = 0;
$count = split(/-/, $string) - 1;       # Evaluate split in a scalar context
print($count . "\n");
			

Return index of certain character

#!bin/perl
use v5.10;                                     # Enable 'say' instead of 'print'
use strict;
use warnings;

my $string = "012345678901234567890123456789";

my $index_of_five = index($string, "5");                    # Index of "5"
say("First index of five: " . $index_of_five);

$index_of_five = index($string, "5", $index_of_five + 1);   # Index with offset
say("Second index of five: " . $index_of_five);

while($string =~ m/6/g) {                                   # Global match (all)
    my $index_of_six = pos($string) - 1;                    # Returns regex pos
    say("Index of six: " . $index_of_six);
}
			

Replace characters in a string

#!bin/perl
use v5.10;
use strict;
use warnings;

my $string = "A-B-C-D-E-F";
say("Original string: " . $string);

# Use transliterator operator (tr)
$string =~ tr/-/x/;          
say("Translated string: " . $string);

# Use substitution operator (s)
$string =~ s/x/+/g;            
say("Substitued string: " . $string);

# Replace substring of 1 character at index where we find a '+', with ' '
my $idx = 0;
while (($idx = index($string, "+", $idx)) != -1) {
    substr($string, $idx, 1, " ");
    $idx++;
}
say("Replaced using substr(): " . $string);

# Split the string on space and join it again with "@" as delimiter
say("Split and joined: " . join("@", (split(/ /, $string))));

			

Pack/Unpack

#!bin/perl
use v5.10;
use strict;
use warnings;

my $string = "ABC";
my $binary_string = unpack("B*", $string);  # Convert string to binary
my $hex_string = unpack("H*", $string);     # Convert string to hexadecimal
my $ascii_string = unpack("a*", $string);   # Convert string to ASCII

say("Binary: " . $binary_string);
say("Hex: " . $hex_string);
say("ASCII: " . $ascii_string);

my $another_string = pack("B*", $binary_string);    # Convert binary to string

die unless $another_string eq $ascii_string;
			

List operations

Adding and removing elements

#!bin/perl
use v5.10; # For say
use strict;
use warnings;

my @array = (1,2,3,4,5);                    # Five (5) elements
say("Array: " . join(",", @array));
say("Array has " . @array . " elements");   

# shift and pop
my $first_value = shift(@array);            # Remove first element
my $last_value = pop(@array);               # Remove last element

say("First value is $first_value");         # 1
say("Last value is $last_value");           # 5
say("Array has " . @array . " elements");   # Three (3)

# unshift and push
unshift(@array, 1);                         # Undo shift (add first element)
push(@array, 5);                            # Add a new last element

say("Array has " . @array . " elements again");   # Five (5)
say("Array: " . join(",", @array));
		

Classes

A simple class

#!/usr/bin/perl

# This is the class declaration

package animal;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $self  = { @_ };
    return bless $self, $class;	
}

sub set_color {
    my $self = shift;
    my $new_color = shift;
    $self->{color} = $new_color;
}

sub describe {
    my $self = shift;
    print("A " . $self->{color} . " " . $self->{species} . " of " . $self->{weight} . " kg\n");
}
# End of class declaration


# This is the main program
package main;

my $kitty = animal->new(
                        species => "cat", 
                        color => "blue", 
                        weight => 40
                        );
$kitty->describe();

$kitty->set_color("red");
$kitty->describe();

Oneliners

Replace in file

perl -p -i -e "s/text_to_replace//g" file