Perl Introduction

by "Blag" - Senior Developer Evangelist

Return to Geeky Thursday

What is Perl?


Perl is a family of high-level, general-purpose, interpreted, dynamic programming languages. The languages in this family includes Perl 5 and Perl 6.

Perl is not an acronym.

Developed by Larry Wall on 1987.

Perl 6 is a redesign on Perl 5 and its considered a separate language.

Perl 5 is used for graphics programming, system administration, network programming, finance, bioinformatics and other applications.

Perl has been nicknamed "the Swiss Army chainsaw of scripting languages".

How to install Perl?


If you're using Linux or Mac...then you have Perl already installed...


If you're using Windows, the best options are Strawberry Perl and Active Perl

Who uses Perl?


  • IMDB - Internet Movies Data Base
  • Amazon
  • BBC - British Broadcasting Corporation
  • Booking.com
  • Duckduckgo - Search Engine
  • Yahoo!

Starting out...


While Perl can be used in interactive mode by doing

perl -de1

It's better to use an text editor as some directives are needed...

Specially when you begin Perl programming...

				
#!/usr/bin/perl

use strict;

use warnings;

use diagnostics;				
				
				

We will use those in every Perl application.

They will force us to declare variables and will find errors at compilation time...

Package Management


Perl has by far the best package management around and it's called CPAN

Although I prefer CPANM which can be installed like this...

cpan App::cpanminus

After that...install any module like this...

cpanm Module::Name

And why I'm saying that CPAN is the best? Well...

  • 174,630 Perl Modules
  • 34,527 distributions
  • 12,887 authors
  • Mirrored on 257 servers

Basic Concepts


Comments are done by using "#".


Each line must be ended by a ";".


Precedence must be enforced by parenthesis


				
print(2*3+5);

11


print(2*(3+5));

16
				

Basic Concepts


Printing on the screen is easy...


				
my $text = "This is perl!";



print($text); 



This is perl!
				

Variables can have multi-assignments...


				
my ($a, $b, $c) = (1, 2, 3);


print("$a $b $c");


1 2 3
				

Data Structures


Perl uses sigils to diferentiate data structures

And variables should be declared using "my"

				
my $s_variable = "This is a string variable";


my $i_variable = 2016;


my @array = (1, 2, 3);


my @another_array = qw(1 2 3);


my %hash = ('1' => 'First', '2' => 'Second');
				

Arrays and Hashes


To access arrays and hashes we need to use a different format

				
my @array = (1, 2, 3);


print "$array[0]\n";


1



my %hash = ('1' => 'First', '2' => 'Second');


print "$hash{1}\n";


First

				

We can also create nested structures, but for this we need to create "references"

				
my @first_array = qw(1 2 3);


my @second_array = qw(a b c);


my @big_array = (\@first_array, \@second_array);


print $big_array[0]->[0];


1


print $big_array[1]->[0];


a
				

Operations on Arrays

				
my @array = (1, 2, 3);


print join ", ", @array;


1 2 3



push @array, 4;


print join ", ", @array;


1 2 3 4
				

Operations on Arrays

				
unshift @array, 0;


print join ", ", @array;


0 1 2 3 4



pop @array;


print join ", ", @array;


0 1 2 3
				

Functions

Functions must always return a value...even when this function doesn't return anything...

				
sub hello{
	
	
	my $name = shift;
	
	
	return "Hello $name!\n";

}
				

shift is used to grab a parameter

				
sub bye{


	my $name = shift;


	print "Bye, $name\n";


	return;


}


print(hello('Blag'));


print(bye('Blag'));



Hello Blag!

Bye, Blag

				

Using more than one parameter

				
sub hello{
	
	
    my ($name, $feeling) = @_;
	
	
    return "Hello $name!, I can see you're feeling",
	
	
           " $feeling!";


}



print(hello('Blag','Happy'));



Hello Blag!, I can see you're feeling Happy!
				

But they can return more than one value...

				
sub operation{


    my ($num1, $num2) = @_;


    return (($num1 + $num2),($num1 * $num2));


}



my ($sum, $mult) = operation(3,3);



print "The sum is $sum and",

      
      "the multiplication is $mult";



The sum is 6 and the multiplication is 9
				

grep and map


These are pretty powerful commands that will save us a lot of time...

				
my @input_numbers = (1, 2, 4, 8, 16, 32, 64);



my @result = map $_ + 100, @input_numbers;

print join ', ', @result;


101, 102, 104, 108, 116, 132, 164



my @bigger_than_ten = grep $_ > 10, @input_numbers;

print join ', ', @bigger_than_ten;


16, 32, 64

				

Fibonacci List


Finally...we're going to make our first application...


So grab your favorite text editor and get ready...


Name your file "Fibonacci.pl"


				
#!/usr/bin/perl

use strict;

use warnings;

use diagnostics;
				
				
sub fib {

    my ($num,$a,$b) = @_;

    my $result = q{};

    if ($a>0 && $num>1){

        $result = $result . ($a+$b) . q{ } . 
        
        fib($num-1,$a+$b,$a)

    }elsif($a == 0){

        $result = $a . q{ } . $b . q{ } . 
        
        ($a+$b) . q{ } . fib($num-1,$a+$b,$b)

    }

    return $result

}
				
				
print "Enter a number: ";


my $num = <>;


print(fib($num,0,1),"\n");
				

Open the Terminal and go to your source code folder...

perl "Name_of_File.pl"


When we run it we're going to see...

Making an LED Number App


This is one of my favorite codes of all time...


Name your file "LED_Numbers.pl"


				
#!/usr/bin/perl

use strict;

use warnings;

use diagnostics;
				
				
my %leds = (

    '0' => ' _  ,| | ,|_| ',

    '1' => '  ,| ,| ',

    '2' => ' _  , _| ,|_  ',

    '3' => '_  ,_| ,_| ',

    '4' => '    ,|_| ,  | ',

    '5' => ' _  ,|_  , _| ',

    '6' => ' _  ,|_  ,|_| ',

    '7' => '_   , |  , |  ',

    '8' => ' _  ,|_| ,|_| ',

    '9' => ' _  ,|_| , _| '

);
				
				
print "Enter a number: ";

my $num = <>;

my @numbers = ( $num =~ /\d/g );



for my $i (0 .. 2){

    for my $j (0 .. scalar(@numbers) - 1){

        my @line = split /\,/,$leds{$numbers[$j]};

        print $line[$i];

    }

    print "\n";

}
				

When we run it we're going to see...


Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime


Name your file "Random_Names.pl"


				
#!/usr/bin/perl

use strict;

use warnings;

use diagnostics;

use Time::HiRes qw(time);

				

For this to work you need to use



cpanm Time::HiRes

				
my $start_run = time;


my @names = qw(

Anne Gigi Blag Juergen Marek Ingo Lars Julia

Danielle Rocky Julien Uwe Myles Mike Steven Fanny

);


my @last_names = qw(

Hardy Read Tejada Schmerder Kowalkiewicz Sauerzapf

Karg Satsuta Keene Ongkowidjojo Vayssiere Kylau

Fenlon Flynn Taylor Tan

);
			
				
my @full_names;

my $full_name;



foreach (1..1000000){

	$full_name = $names[0 + int rand(16)] . q{ } . 
	
	             $last_names[0 + int rand(16)];

	push @full_names, $full_name;

}



my $end_run = time;


print "Time: ", $end_run - $start_run, "\n";

print scalar @full_names, " names generated\n";
			

When we run it we're going to see...

How this behaves in Python?

And in Julia?

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


This will include some nice commands...


Name your file "decimal_to_romans.pl"


				
#!/usr/bin/perl

use strict;

use warnings;

use diagnostics;
			
				
my %roman_table = (

'1000' => 'M', '900' => 'CM', '500' => 'D',

'400' => 'CD', '100' => 'C', '90' => 'XC',

'50' => 'L', '40' => 'XL', '10' => 'X',

'9' => 'IX', '5' => 'V', '4' => 'IV', '1' => 'I'

);
			
				
sub roman_number{
	
    my $number = shift; my $result;
    
    my @sorted = sort { $b <=> $a } keys %roman_table;
    
    until($number == 0){
    
        foreach my $value (@sorted){
    
           if($number >= $value){
    
              $result = $result . $roman_table{$value};
    
              $number -= $value;
    
              last;
    
           }
    
        }
    
    }
    
    return $result;
    
}
				
				
print "Enter a number: ";

my $num = <>;

my $result = roman_number($num);

print "$result\n";
				

When we run it we're going to see...


Count Letters


In this example we're going to read a file and count how many time a letter appears...


Call your file "countletters.pl" (all in lowercase).


Create a file called "readme.txt" with the following text...


"This is a text file that we're going to read it using perl"


				
#!/usr/bin/perl

use strict;

use warnings;

use diagnostics;
			
				
open(my $fh, "<", "readme.txt") 

or die "Can't open readme.txt: $!";

my $line = <$fh>;

my @letters = split //, $line;

my %counter;
			
				
foreach my $letter (@letters){

    $counter{$letter} = ($counter{$letter} or 0) + 1;

}


while(my ($key, $value) = each %counter){
    
    print "$key => $value\n";

}


close $fh;
			

When we run it we're going to see...


That's it for now


Perl is a rich and awesome language


But also, it can be very complex, so look for some books and tutorials to keep learning


Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...