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

What's hot (20)

PDF
DBIx::Class beginners
leo lapworth
 
ODP
Introducing Modern Perl
Dave Cross
 
ODP
Introduction to Perl
Dave Cross
 
PPT
Javascript arrays
Hassan Dar
 
PPT
LPW: Beginners Perl
Dave Cross
 
PDF
PHP Unit 4 arrays
Kumar
 
ODP
Advanced Perl Techniques
Dave Cross
 
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PDF
Quick flask an intro to flask
juzten
 
PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
Perl Scripting
Varadharajan Mukundan
 
PPTX
Presentation on overloading
Charndeep Sekhon
 
PPT
Python Dictionaries and Sets
Nicole Ryan
 
PPT
PHP Tutorials
Yuriy Krapivko
 
PPTX
Php basics
Jamshid Hashimi
 
PPT
cascading style sheet ppt
abhilashagupta
 
PDF
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
PDF
OOP in PHP
Alena Holligan
 
PDF
Introduction to CSS
Prarthan P
 
DBIx::Class beginners
leo lapworth
 
Introducing Modern Perl
Dave Cross
 
Introduction to Perl
Dave Cross
 
Javascript arrays
Hassan Dar
 
LPW: Beginners Perl
Dave Cross
 
PHP Unit 4 arrays
Kumar
 
Advanced Perl Techniques
Dave Cross
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Quick flask an intro to flask
juzten
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
Perl Scripting
Varadharajan Mukundan
 
Presentation on overloading
Charndeep Sekhon
 
Python Dictionaries and Sets
Nicole Ryan
 
PHP Tutorials
Yuriy Krapivko
 
Php basics
Jamshid Hashimi
 
cascading style sheet ppt
abhilashagupta
 
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
OOP in PHP
Alena Holligan
 
Introduction to CSS
Prarthan P
 

Viewers also liked (9)

ODP
Perl Introduction
Marcos Rebelo
 
PDF
Perl programming language
Elie Obeid
 
PPT
Introduction To Catalyst - Part 1
Dan Dascalescu
 
PDF
Perl hosting for beginners - Cluj.pm March 2013
Arpad Szasz
 
ODP
Introduction to Web Programming with Perl
Dave Cross
 
PDF
DBI Advanced Tutorial 2007
Tim Bunce
 
ODP
Database Programming with Perl and DBIx::Class
Dave Cross
 
PPTX
Lagrange’s interpolation formula
Mukunda Madhav Changmai
 
PPTX
Cookie and session
Aashish Ghale
 
Perl Introduction
Marcos Rebelo
 
Perl programming language
Elie Obeid
 
Introduction To Catalyst - Part 1
Dan Dascalescu
 
Perl hosting for beginners - Cluj.pm March 2013
Arpad Szasz
 
Introduction to Web Programming with Perl
Dave Cross
 
DBI Advanced Tutorial 2007
Tim Bunce
 
Database Programming with Perl and DBIx::Class
Dave Cross
 
Lagrange’s interpolation formula
Mukunda Madhav Changmai
 
Cookie and session
Aashish Ghale
 
Ad

Similar to Introduction to Perl - Day 2 (20)

ODP
Intermediate Perl
Dave Cross
 
ODP
Beginning Perl
Dave Cross
 
PPT
Perl Presentation
Sopan Shewale
 
ODP
Introduction to Modern Perl
Dave Cross
 
ODP
What's new, what's hot in PHP 5.3
Jeremy Coates
 
PPT
Bioinformatica 10-11-2011-p6-bioperl
Prof. Wim Van Criekinge
 
PPTX
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
PPT
Cleancode
hendrikvb
 
PDF
Introduction to Perl
worr1244
 
PPT
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
PPT
PHP
webhostingguy
 
ODP
Advanced Perl Techniques
Dave Cross
 
PDF
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
PPT
Hashes Master
Paolo Marcatili
 
PPTX
PHP and Cassandra
Dave Gardner
 
PPT
Introduction to perl_lists
Vamshi Santhapuri
 
PPT
Php Using Arrays
mussawir20
 
PDF
Learning Perl 6
brian d foy
 
PPTX
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
Intermediate Perl
Dave Cross
 
Beginning Perl
Dave Cross
 
Perl Presentation
Sopan Shewale
 
Introduction to Modern Perl
Dave Cross
 
What's new, what's hot in PHP 5.3
Jeremy Coates
 
Bioinformatica 10-11-2011-p6-bioperl
Prof. Wim Van Criekinge
 
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
Cleancode
hendrikvb
 
Introduction to Perl
worr1244
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
Advanced Perl Techniques
Dave Cross
 
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
Hashes Master
Paolo Marcatili
 
PHP and Cassandra
Dave Gardner
 
Introduction to perl_lists
Vamshi Santhapuri
 
Php Using Arrays
mussawir20
 
Learning Perl 6
brian d foy
 
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
 
Ad

More from Dave Cross (20)

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

Recently uploaded (20)

PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 

Introduction to Perl - Day 2