Perl
Table of Contents
Introduction
Philosophy
Perl is an interpreted language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It's also a good language for many system management tasks. The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). It combines (in the author's opinion, anyway) some of the best features of C, sed, awk, and sh, so people familiar with those languages should have little difficulty with it.
Perl 5 includes a number of features which make Perl a general-purpose programming language. Examples for this are support for Object Oriented Programming, Unicode, database integration, etc. (What is Perl? ).
Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English.
(http://perldoc.perl.org/perlsyn.html)
- There is more then one way to do it (TIMTOWTDI)
- Do what I mean (DWIM)
Hello World
use strict; use warnings; print "Hello, world";
Sources of information
Shortcuts
These are the most important bookmarks for me personally:
Official documentation
Basics
Data types
Scalars
my $string = 'text'; my $integer = 42; my $float = 3.14; say $string; say $integer; say $float;
- Functions
Functions for SCALARs or strings | perldoc.perl.org
- substr
- index
- chomp
Arrays
- Fundamental operations
# Declare array my @elements = ('one', 'two', 'tree', 'four'); # Access elements say $elements[0]; say $elements[1]; say $elements[2]; say $elements[3]; # Get array size say 'Number of elements: ' . @elements;
See http://modernperlbooks.com/books/modern_perl_2014/03-perl-language.html#QXJyYXlBc3NpZ25tZW50
- Element manipulation
- pop: remove and return the last element
- shift: remove and return the first element
- push: add element(s) at the tail
- unshift: add element(s) at the top
- Sort elements
Sort acending:
my @ascending_sorted_list = sort {$a <=> $b} @original_list;
Sort descending:
my @descending_sorted_list = sort {$b <=> $a} @original_list;
Using a custom sort function:
sub cmp_value { return $a <=> $b; } my @sorted_elements = sort cmp_value @elements;
- Functions
http://perldoc.perl.org/index-functions-by-cat.html#Functions-for-real-@ARRAYs
- grep
- join: Create a string out of an array
- map
- qw//
- reverse
- unpack
- Read more
Hashes
References
- Basic example
my %combination; $combination{25} = 0; $combination{10} = 0; $combination{ 5} = 0; $combination{ 1} = 0; $combination{25} += 3; my $cref = \%combination; $cref->{25} -= 1; say Dumper(%combination);
- How to dereference a list?
my @list = (25, 20, 5, 1); my $list_ref = \@list; for my $element (@{$list_ref}) say $element; }
- How to dereference a hash reference?
Constants
http://perldoc.perl.org/constant.html
use constant US_COINS => { QUARTERS => 25, DIMES => 10, NICKELS => 5, PENNIES => 1 }; for my $name (keys US_COINS) { say $name; } say US_COINS->{'QUARTERS'};
Flow control
http://perldoc.perl.org/perlsyn.html#Compound-Statements http://perldoc.perl.org/perlintro.html#Conditional-and-looping-constructs
Conditionals
my $false_1 = 0; my $false_2 = '0'; my $false_3 = ''; my $false_4 = (); my $false_5 = undef; my $true = 'rest'; if ($false_1) { say 'if block executed'; } elsif ($true) { say 'elsif block executed'; } else { say 'else block executed'; }
Loops
http://perldoc.perl.org/perlsyn.html#Loop-Control
- for / foreach : http://perldoc.perl.org/perlsyn.html#Foreach-Loops
- next, do, last, continue : http://perldoc.perl.org/perlsyn.html#Loop-Control
- next: go the next loop iteration
- last: exit the loop
- redo: restart the loop
- while
my @list = ('one', 'two', 'three'); while (@list) { say shift @list; }
- for
http://perldoc.perl.org/perlsyn.html#For-Loops This is the Perl way for for-loops:
for (1..10) { say 'Counter: ' . $_; }
However, C-style loops could be used as well:
for (my $i = 0; $i < 10; $i++) { say 'Counter: ' . ($i + 1); }
- foreach
For and foreach can be used as synonyms.
- Labels and continue
while, until and for loops support labels in order to control the loop execution.
Modules
Functions
How to export a function from a module?
- Default parameters
http://modernperlbooks.com/books/modern_perl_2014/04-perl-operators.html#TG9naWNhbE9wZXJhdG9ycw
sub function { my ($var_1, $var_2) = @_; $var_2 = $var_2 // 42; say $var_1; say $var_2; } function('test', '84');
Packages
package Local::Anagrams; use strict; use warnings; use Exporter 'import'; our @EXPORT_OK = qw/ get_permutations /; sub get_permutations my $string = shift; # ... return @permutations; } 1;
Intermediary
Text operations
How to compare strings?
if ($var eq "text") { print '$var equals "text"'; }
Regular expressions
Input and output
How to write files?
Terminal
Commandline parameters
The simplest way to read command line arguments is via the special variable '@ARGV'.
use strict; use warnings; require 'anagrams.pm'; use feature 'say'; if (@ARGV != 1) { say 'Usage: get_anagrams.pl <word>'; exit 1; } foreach my $word (get_permutations($ARGV[0])) { say $word; }
Read more:
Date and time
Object orientation
bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use
Unit tests
Test::Simple
https://metacpan.org/pod/Test::Simple
use strict; use warnings; use Test::Simple tests => 1; sub add { my ($a, $b) = @_; return $a + $b; } ok(add(1,2) == 3, 'Simple addition calculated correctly.');
Test::More
https://metacpan.org/pod/Test::More
use strict; use warnings; use Test::More tests => 2; use Local::List; my @example_list = (6,1,34,3,12); my $min_value = min(@example_list); cmp_ok($min_value, '==', 1); my $max_value = max(@example_list); cmp_ok($max_value, '==', 34)
Advanced
Performance optimization
Multithreading
Miscellaneous
System commands
Special variables
- http://www.perlmonks.org/?node_id=353259
- Special Vars Quick Reference | perlmonks.org
Variable scope
Rounding
Math::Round
use strict; use warnings; use Math::Round; #http://search.cpan.org/~grommel/Math-Round-0.06/Round.pm my $f = 3.1415926535; my $r = printf("%.3f", 3.1415926535); print "$r\n";
POSIX
use strict; use warnings; use feature 'say'; use POSIX qw (floor ceil); my $float = 1.234; say floor($float); say ceil($float); # https://metacpan.org/pod/distribution/perl/ext/POSIX/lib/POSIX.pod
Use English
http://perldoc.perl.org/English.html
With 'use English' it is possible to use English terms for special variables etc.
use English;
Data::Dumper
https://metacpan.org/pod/Data::Dumper
use strict; use warnings; use feature 'say'; use Data::Dumper; my %example_hash; $example_hash{key1} = 'value1'; $example_hash{key2} = 'value2'; say Dumper(%example_hash);