SlideShare a Scribd company logo
Introduction to Perl Day 2 An Introduction to Perl Programming Dave Cross Magnum Solutions Ltd [email_address]
What We Will Cover Types of variable
Strict and warnings
References
Sorting
Reusable Code
Object Orientation
What We Will Cover Testing
Dates and Times
Templates
Databases
Further Information
Schedule 09:30 – Begin
11:00 – Coffee break (30 mins)
13:00 – Lunch (90 mins)
14:30 – Begin
16:00 – Coffee break (30 mins)
18:00 – End
Resources Slides available on-line http://mag-sol.com/train/public/2009/yapc Also see Slideshare http://www.slideshare.net/davorg/slideshows Get Satisfaction http://getsatisfaction.com/magnum
Types of Variable
Types of Variable Perl variables are of two types
Important to know the difference
Lexical variables are created with  my
Package variables are created by  our
Lexical variables are associated with a code block
Package variables are associated with a package
Lexical Variables Created with  my
my ($doctor, @timelords,   %home_planets);
Live in a pad (associated with a block of code) Piece of code delimited by braces
Source file Only visible within enclosing block
"Lexical" because the scope is defined purely by the text
Packages All Perl code is associated with a package
A new package is created with package package MyPackage; Think of it as a namespace
Used to avoid name clashes with libraries
Default package is called main
Package Variables Live in a package's symbol table
Can be referred to using a fully qualified name $main::doctor
@Gallifrey::timelords Package name not required within own package
Can be seen from anywhere in the package (or anywhere at all when fully qualified)
Declaring Package Vars Can be predeclared with  our
our ($doctor, @timelords,   %home_planet);
Or (in older Perls) with  use vars
use vars qw($doctor   @timelords   %home_planet);
Lexical or Package When to use lexical variables or package variables?
Simple answer Always use lexical variables More complete answer Always use lexical variables
Except for a tiny number of cases http://perl.plover.com/local.html
local You might see code that uses local
local $variable;
This doesn't do what you think it does
Badly named function
Doesn't create local variables
Creates a local copy of a package variable
Can be useful In a small number of cases
local Example $/  is a package variable
It defines the record separator
You might want to change it
Always localise changes
{   local $/ = “\n\n”;   while (<FILE> ) {   ...   } }
Strict and Warnings
Coding Safety Net Perl can be a very loose programming language
Two features can minimise the dangers
use strict  /  use warnings
A good habit to get into
No serious Perl programmer codes without them
use strict Controls three things
use strict 'refs'  – no symbolic references
use strict 'subs'  – no barewords
use strict 'vars'  – no undeclared variables
use strict  – turn on all three at once
turn them off (carefully) with  no strict
use strict 'refs' Prevents symbolic references
aka &quot;using a variable as another variable's name&quot;
$what = 'dalek'; $$what = 'Karn'; # sets $dalek to 'Karn'
What if 'dalek' came from user input?
People often think this is a cool feature
It isn't
use strict 'refs' (cont) Better to use a hash
$what = 'dalek'; $alien{$what} = 'Karn';
Self contained namespace
Less chance of clashes
More information (e.g. all keys)
use strict 'subs' No barewords
Bareword is a word with no other interpretation
e.g. word without $, @, %, &
Treated as a function call or a quoted string
$dalek = Karn;
May clash with future reserved words
use strict 'vars' Forces predeclaration of variable names
Prevents typos
Less like BASIC - more like Ada
Thinking about scope is good
use warnings Warns against dubious programming habits
Some typical warnings Variables used only once
Using undefined variables
Writing to read-only file handles
And many more...
Allowing Warnings Sometimes it's too much work to make code warnings clean
Turn off use warnings locally
Turn off specific warnings
{   no warnings 'deprecated';   # dodgy code ... }
See perldoc perllexwarn
References
Introducing References A reference is a bit like pointer in languages like C and Pascal (but better)
A reference is a unique way to refer to a variable.
A reference can always fit into a scalar variable
A reference looks like  SCALAR(0x20026730)
Creating References Put \ in front of a variable name $scalar_ref = \$scalar;
$array_ref = \@array;
$hash_ref = \%hash; Can now treat it just like any other scalar $var = $scalar_ref;
$refs[0] = $array_ref;
$another_ref = $refs[0];
Creating References [ LIST ]  creates anonymous array and returns a reference
$aref = [ 'this', 'is', 'a', 'list']; $aref2 = [ @array ];
{ LIST }  creates anonymous hash and returns a reference
$href = { 1 => 'one', 2 => 'two' }; $href = { %hash };
Creating References @arr = (1, 2, 3, 4); $aref1 = \@arr; $aref2 = [ @arr ]; print &quot;$aref1\n$aref2\n&quot;;
Output ARRAY(0x20026800) ARRAY(0x2002bc00)
Second method creates a  copy  of the array
Using Array References Use  {$aref}  to get back an array that you have a reference to
Whole array
@array = @{$aref};
@rev = reverse @{$aref};
Single elements
$elem = ${$aref}[0];
${$aref}[0] = 'foo';
Using Hash References Use  {$href}  to get back a hash that you have a reference to
Whole hash
%hash = %{$href};
@keys = keys %{$href};
Single elements
$elem = ${$href}{key};
${$href}{key} = 'foo';
Using References Use arrow ( -> ) to access elements of arrays or hashes
Instead of  ${$aref}[0]  you can use $aref->[0]
Instead of  ${$href}{key}  you can use $href->{key}
Using References You can find out what a reference is referring to using ref
$aref = [ 1, 2, 3 ]; print ref $aref; # prints ARRAY
$href = { 1 => 'one',   2 => 'two' }; print ref $href; # prints HASH
Why Use References? Parameter passing
Complex data structures
Parameter Passing What does this do?
@arr1 = (1, 2, 3); @arr2 = (4, 5, 6); check_size(@arr1, @arr2); sub check_size {   my (@a1, @a2) = @_;   print @a1 == @a2 ?   'Yes' : 'No'; }
Why Doesn't It Work? my (@a1, @a2) = @_;
Arrays are combined in  @_
All elements end up in  @a1
How do we fix it?
Pass references to the arrays
Another Attempt @arr1 = (1, 2, 3); @arr2 = (4, 5, 6); check_size(\@arr1, \@arr2); sub check_size {   my ($a1, $a2) = @_;   print @$a1 == @$a2 ?   'Yes' : 'No'; }
Complex Data Structures Another good use for references
Try to create a 2-D array
@arr_2d = ((1, 2, 3),   (4, 5, 6),   (7, 8, 9));
@arr_2d contains (1, 2, 3, 4, 5, 6, 7, 8, 9)
This is known a  array flattening
Complex Data Structures 2D Array using references
@arr_2d = ([1, 2, 3],   [4, 5, 6],   [7, 8, 9]);
But how do you access individual elements?
$arr_2d[1]  is ref to array (4, 5, 6)
$arr_2d[1]->[1]  is element 5
Complex Data Structures Another 2D Array
$arr_2d = [[1, 2, 3],   [4, 5, 6],   [7, 8, 9]];

More Related Content

ODP
Introduction to Perl - Day 1
ODP
Perl Introduction
PPTX
OCL tutorial
PDF
Functional programming
PDF
Introduction to RapidMiner Studio V7
PPTX
Regular Expression (Regex) Fundamentals
KEY
Clean Code
Introduction to Perl - Day 1
Perl Introduction
OCL tutorial
Functional programming
Introduction to RapidMiner Studio V7
Regular Expression (Regex) Fundamentals
Clean Code

What's hot (20)

PPT
Introduction To Catalyst - Part 1
ODP
Introducing Modern Perl
PDF
DBIx::Class beginners
PPT
Php with MYSQL Database
PPT
LPW: Beginners Perl
PDF
Web 2 | CSS - Cascading Style Sheets
PPT
Introduction to Javascript
ODP
Database Programming with Perl and DBIx::Class
PPT
Control Structures In Php 2
PPTX
Php by shivitomer
PPT
Javascript
PPSX
Php and MySQL
PPT
Oops concepts in php
PPT
JavaScript - An Introduction
PPT
JavaScript & Dom Manipulation
PPT
PHP POWERPOINT SLIDES
PPT
01 Php Introduction
PPTX
Javascript
PPT
JavaScript Tutorial
PPT
Introduction To Catalyst - Part 1
Introducing Modern Perl
DBIx::Class beginners
Php with MYSQL Database
LPW: Beginners Perl
Web 2 | CSS - Cascading Style Sheets
Introduction to Javascript
Database Programming with Perl and DBIx::Class
Control Structures In Php 2
Php by shivitomer
Javascript
Php and MySQL
Oops concepts in php
JavaScript - An Introduction
JavaScript & Dom Manipulation
PHP POWERPOINT SLIDES
01 Php Introduction
Javascript
JavaScript Tutorial
Ad

Viewers also liked (7)

PDF
Perl programming language
PDF
Perl Scripting
PDF
Perl hosting for beginners - Cluj.pm March 2013
ODP
Introduction to Web Programming with Perl
PDF
DBI Advanced Tutorial 2007
PPTX
Lagrange’s interpolation formula
PPTX
Cookie and session
Perl programming language
Perl Scripting
Perl hosting for beginners - Cluj.pm March 2013
Introduction to Web Programming with Perl
DBI Advanced Tutorial 2007
Lagrange’s interpolation formula
Cookie and session
Ad

Similar to Introduction to Perl - Day 2 (20)

ODP
Intermediate Perl
PPTX
Marcs (bio)perl course
ODP
Introduction to Perl
ODP
Beginning Perl
PDF
Cs3430 lecture 17
PDF
Marc’s (bio)perl course
PDF
Scripting3
PDF
Introduction to Perl
PPT
You Can Do It! Start Using Perl to Handle Your Voyager Needs
PPTX
PERL PROGRAMMING LANGUAGE Basic Introduction
PPTX
Lecture 3 Perl & FreeBSD administration
PDF
Learning Perl 6
PPT
PERL.ppt
PPTX
Data structure in perl
PDF
perl 6 hands-on tutorial
PDF
Tutorial perl programming basic eng ver
PDF
Learning Perl 6 (NPW 2007)
PPT
Crash Course in Perl – Perl tutorial for C programmers
Intermediate Perl
Marcs (bio)perl course
Introduction to Perl
Beginning Perl
Cs3430 lecture 17
Marc’s (bio)perl course
Scripting3
Introduction to Perl
You Can Do It! Start Using Perl to Handle Your Voyager Needs
PERL PROGRAMMING LANGUAGE Basic Introduction
Lecture 3 Perl & FreeBSD administration
Learning Perl 6
PERL.ppt
Data structure in perl
perl 6 hands-on tutorial
Tutorial perl programming basic eng ver
Learning Perl 6 (NPW 2007)
Crash Course in Perl – Perl tutorial for C programmers

More from Dave Cross (20)

PDF
Measuring the Quality of Your Perl Code
PDF
Apollo 11 at 50 - A Simple Twitter Bot
PDF
Monoliths, Balls of Mud and Silver Bullets
PPTX
The Professional Programmer
PDF
I'm A Republic (Honest!)
PDF
Web Site Tune-Up - Improve Your Googlejuice
PDF
Modern Perl Web Development with Dancer
PDF
Freeing Tower Bridge
PDF
Modern Perl Catch-Up
PDF
Error(s) Free Programming
PDF
Medium Perl
PDF
Modern Web Development with Perl
PDF
Improving Dev Assistant
PDF
Conference Driven Publishing
PDF
Conference Driven Publishing
PDF
TwittElection
PDF
Perl in the Internet of Things
PDF
Return to the Kingdom of the Blind
PDF
Github, Travis-CI and Perl
ODP
Object-Oriented Programming with Perl and Moose
Measuring the Quality of Your Perl Code
Apollo 11 at 50 - A Simple Twitter Bot
Monoliths, Balls of Mud and Silver Bullets
The Professional Programmer
I'm A Republic (Honest!)
Web Site Tune-Up - Improve Your Googlejuice
Modern Perl Web Development with Dancer
Freeing Tower Bridge
Modern Perl Catch-Up
Error(s) Free Programming
Medium Perl
Modern Web Development with Perl
Improving Dev Assistant
Conference Driven Publishing
Conference Driven Publishing
TwittElection
Perl in the Internet of Things
Return to the Kingdom of the Blind
Github, Travis-CI and Perl
Object-Oriented Programming with Perl and Moose

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Sensors and Actuators in IoT Systems using pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Empathic Computing: Creating Shared Understanding
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Advanced Soft Computing BINUS July 2025.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Reach Out and Touch Someone: Haptics and Empathic Computing
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Sensors and Actuators in IoT Systems using pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Empathic Computing: Creating Shared Understanding
Chapter 2 Digital Image Fundamentals.pdf
Spectral efficient network and resource selection model in 5G networks
Advanced methodologies resolving dimensionality complications for autism neur...
Advanced Soft Computing BINUS July 2025.pdf

Introduction to Perl - Day 2