SlideShare a Scribd company logo
Introduction to Perl An Introduction to Perl Programming Dave Cross Magnum Solutions Ltd [email_address]
What We Will Cover What is Perl?
Creating and running a Perl program
Input and Output
Perl variables
Operators and Functions
Conditional Constructs
What We Will Cover Subroutines
Regular Expressions
References
Smart Matching
Finding and using Modules
Further Information
Schedule 09:45 – Begin
11:15 – Coffee break
13:00 – Lunch
14:00 – Begin
15:30 – Coffee break
17:00 – End
Resources Slides available on-line http://mag-sol.com/train/public/2009-02/begin Also see Slideshare http://www.slideshare.net/davorg/slideshows Mailing List http://lists.mag-sol.com/mailman/listinfo/beg2009 Get Satisfaction http://getsatisfaction.com/magnum
What is Perl?
Perl's Name Practical Extraction and Reporting Language
Pathologically Eclectic Rubbish Lister
"Perl" is the language
"perl" is the compiler
Never "PERL"
Typical uses of Perl Text processing
System administration tasks
CGI and web programming
Database interaction
Other Internet programming
Less typical uses of Perl Human Genome Project
NASA
What is Perl Like? General purpose programming language
Free (open source)‏
Fast
Flexible
Secure
Fun
The Perl Philosophy There's more than one way to do it
Three virtues of a programmer Laziness
Impatience
Hubris Share and enjoy!
Creating and Running a Perl Program
Creating a Perl Program Our first Perl program print "Hello world\n";
Put this in a file called hello.pl
Running a Perl Program Running a Perl program from the command line
$ perl hello.pl
Running a Perl Program The "shebang" line (Unix, not Perl) #!/usr/bin/perl
Make program executable $ chmod +x hello.pl
Run from command line $ ./hello.pl
Perl Comments Add comments to your code
Start with a hash ( # )‏
Continue to end of line
# This is a hello world program print "Hello, world!\n"; # print
Command Line Options Many options to control execution of the program
For example,  -w  turns on warnings
Use on command line perl -w hello.pl
Or on shebang line #!/usr/bin/perl -w
Perl variables
What is a Variable? A place where we can store data
A variable needs a name to retrieve the data stored in it
put new data in it
Variable Names Contain alphanumeric characters and underscores
User variable names may not start with numbers
Variable names are preceded by a punctuation mark indicating the type of data
Types of Perl Variable Different types of variables start with a different symbol Scalar variables start with $
Array variables start with @
Hash variables start with % More on these types soon
Declaring Variables You don't need to declare variables in Perl
But it's a very good idea typos
scoping Using the strict pragma use strict; my $var;
Scalar Variables Store a single item of data
my $name = "Arthur";
my $whoami = 'Just Another Perl Hacker';
my $meaning_of_life = 42;
my $number_less_than_1 = 0.000001;
my $very_large_number = 3.27e17;    # 3.27 times 10 to the power of 17
Type Conversions Perl converts between strings and numbers whenever necessary
Add int to a floating point number my $sum = $meaning_of_life +   $number_less_than_1;
Putting a number into a string   print "$name says, 'The meaning of life is $sum.'\n";
Quoting Strings Single quotes don't expand variables or escape sequences my $price = '$9.95';
Double quotes do my $invline =   "24 widgets @ $price each\n";
Use a backslash to escape special characters in double quoted strings print "He said \"The price is \$300\"";
Better Quotes This can look ugly   print "He said \"The price is \$300\"";
This is a tidier alternative   print qq(He said "The price is \$300");
Also works for single quotes   print q(He said "That's too expensive");
Undefined Values A scalar variable that hasn't had data put into it will contain the special value “undef”
Test for it with “defined()” function
if (defined($my_var)) { ... }
Array Variables Arrays contain an ordered list of scalar values
my @fruit = ('apples', 'oranges',   'guavas', 'passionfruit',   'grapes');
my @magic_numbers = (23, 42, 69);
my @random_scalars = ('mumble', 123.45,   'dave cross',   -300, $name);
Array Elements Accessing individual elements of an array
print $fruits[0]; # prints "apples"
Note: Indexes start from zero
print $random_scalars[2]; # prints "dave cross"
Note use of $ as individual element of an array is a scalar
Array Slices Returns a list of elements from an array
print @fruits[0,2,4]; # prints "apples", "guavas", # "grapes"
print @fruits[1 .. 3]; # prints "oranges", "guavas", # "passionfruit"
Note use of @ as we are accessing more than one element of the array
Setting Array Values $array[4] = 'something'; $array[400] = 'something else';
Also with slices
@array[4, 7 .. 9] = ('four', 'seven',    'eight', 'nine');
@array[1, 2] = @array[2, 1];
Doesn't need to be an array! ($x, $y) = ($y, $x);
Array Size $#array  is the index of the last element in  @array
Therefore  $#array + 1  is the number of elements
$count = @array;  does the same thing and is easier to understand
Hash Variables Hashes implement “look-up tables” or “dictionaries”
Initialised with a list %french = ('one', 'un', 'two', 'deux',   'three', 'trois');
"fat comma" (=>) is easier to understand %german = (one  => 'ein',   two  => 'zwei',    three => 'drei');
Accessing Hash Values $three = $french{three};
print $german{two};
As with arrays, notice the use of $ to indicate that we're accessing a single value
Hash Slices Just like array slices
Returns a list of elements from a hash print @french{'one','two','three'}; # prints "un", "deux" & "trois"
Again, note use of @ as we are accessing more than one value from the hash
Setting Hash Values $hash{foo} = 'something';
$hash{bar} = 'something else';
Also with slices
@hash{'foo', 'bar'} =  ('something', 'else');
@hash{'foo', 'bar'} =  @hash{'bar', 'foo'};
More About Hashes Hashes are not sorted
There is no equivalent to  $#array
print %hash  is unhelpful
We'll see ways round these restrictions later
Special Perl Variables Perl has many special variables
Many of them have punctuation marks as names
Others have names in ALL_CAPS
They are documented in perlvar
The Default Variable Many Perl operations either set  $_  or use its value if no other is given
print; # prints the value of $_
If a piece of Perl code seems to be missing a variable, then it's probably using  $_
Think of “it” or “that” in English
Using $_ while (<FILE>) {   if (/regex/) {   print;   } }
Three uses of $_
A Special Array @ARGV
Contains your programs command line arguments
perl printargs.pl foo bar baz
my $num = @ARGV; print &quot;$num arguments: @ARGV\n&quot;;
A Special Hash %ENV
Contains the  environment variables  that your script has access to.
Keys are the variable names Values are the… well… values!
print $ENV{PATH};
Input and Output
Input and Output Programs become more useful with input and output
We'll see more input and output methods later in the day
But here are some simple methods
Output The easiest way to get data out of a Perl program is to use  print
print “Hello world\n”;
Input The easiest way to get data into a Perl program is to read from  STDIN
$input = <STDIN>;
< ... >  is the “read from filehandle” operator
STDIN  is the standard input filehandle
A Complete Example #!/usr/bin/perl print 'What is your name: '; $name = <STDIN>; print “Hello $name”;
Operators and Functions
Operators and Functions What are operators and functions?
&quot;Things&quot; that do &quot;stuff&quot;
Routines built into Perl to manipulate data
Other languages have a strong distinction between operators and functions in Perl that distinction can be a bit blurred See perlop and perlfunc
Arithmetic Operators Standard arithmetic operations add (+), subtract (-), multiply (*), divide (/)‏
Less standard operations modulus (%), exponentiation (**)‏
$speed = $distance / $time; $vol = $length * $breadth * $height; $area = $pi * ($radius ** 2); $odd = $number % 2;
Shortcut Operators Often need to do things like $total = $total + $amount;
Can be abbreviated to $total += $amount;
Even shorter $x++; # same as $x += 1 or $x = $x + 1 $y--; # same as $y -= 1 or $y = $y - 1

More Related Content

What's hot (20)

PPT
Php Basic
Md. Sirajus Salayhin
 
ODP
Perl Introduction
Marcos Rebelo
 
PPTX
Bioinformatics p1-perl-introduction v2013
Prof. Wim Van Criekinge
 
PPT
P H P Part I, By Kian
phelios
 
ODP
Introduction to Modern Perl
Dave Cross
 
PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
2014 database - course 2 - php
Hung-yu Lin
 
PPT
Perl tutorial
Manav Prasad
 
ODP
Programming in perl style
Bo Hua Yang
 
PPT
Class 5 - PHP Strings
Ahmed Swilam
 
PPT
Introduction To Php For Wit2009
cwarren
 
PPTX
Lecture 2 php basics (1)
Core Lee
 
PPT
slidesharenew1
truptitasol
 
PPT
My cool new Slideshow!
omprakash_bagrao_prdxn
 
ODP
PHP Web Programming
Muthuselvam RS
 
PPT
Php Reusing Code And Writing Functions
mussawir20
 
PPT
Introduction to php
sagaroceanic11
 
PDF
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Perl Introduction
Marcos Rebelo
 
Bioinformatics p1-perl-introduction v2013
Prof. Wim Van Criekinge
 
P H P Part I, By Kian
phelios
 
Introduction to Modern Perl
Dave Cross
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
2014 database - course 2 - php
Hung-yu Lin
 
Perl tutorial
Manav Prasad
 
Programming in perl style
Bo Hua Yang
 
Class 5 - PHP Strings
Ahmed Swilam
 
Introduction To Php For Wit2009
cwarren
 
Lecture 2 php basics (1)
Core Lee
 
slidesharenew1
truptitasol
 
My cool new Slideshow!
omprakash_bagrao_prdxn
 
PHP Web Programming
Muthuselvam RS
 
Php Reusing Code And Writing Functions
mussawir20
 
Introduction to php
sagaroceanic11
 
Zend Certification Preparation Tutorial
Lorna Mitchell
 

Viewers also liked (17)

PDF
Idiotic Perl
Dave Cross
 
ODP
Perl Training
Dave Cross
 
ODP
Intermediate Perl
Dave Cross
 
ODP
Proud To Use Perl
Dave Cross
 
ODP
The Professional Programmer
Dave Cross
 
ODP
Perl Teach-In (part 2)
Dave Cross
 
ODP
Saint Perl 2009: CGI::Ajax demo
megakott
 
PDF
Practical approach to perl day2
Rakesh Mukundan
 
PDF
Achieving the Impossible with Perl
Adam Trickett
 
ZIP
Beginning Kindle Hackery
Jesse Vincent
 
ODP
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
 
PDF
Practical approach to perl day1
Rakesh Mukundan
 
PPT
Perl Basics with Examples
Nithin Kumar Singani
 
ODP
Functional perl
Errorific
 
PDF
Perl University: Getting Started with Perl
brian d foy
 
PDF
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
PDF
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
Idiotic Perl
Dave Cross
 
Perl Training
Dave Cross
 
Intermediate Perl
Dave Cross
 
Proud To Use Perl
Dave Cross
 
The Professional Programmer
Dave Cross
 
Perl Teach-In (part 2)
Dave Cross
 
Saint Perl 2009: CGI::Ajax demo
megakott
 
Practical approach to perl day2
Rakesh Mukundan
 
Achieving the Impossible with Perl
Adam Trickett
 
Beginning Kindle Hackery
Jesse Vincent
 
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
 
Practical approach to perl day1
Rakesh Mukundan
 
Perl Basics with Examples
Nithin Kumar Singani
 
Functional perl
Errorific
 
Perl University: Getting Started with Perl
brian d foy
 
Perl Programming - 02 Regular Expression
Danairat Thanabodithammachari
 
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
 
Ad

Similar to Beginning Perl (20)

ODP
Introduction to Perl - Day 1
Dave Cross
 
PPT
Perl Presentation
Sopan Shewale
 
PPT
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
PPT
CGI With Object Oriented Perl
Bunty Ray
 
PPT
Dealing with Legacy Perl Code - Peter Scott
O'Reilly Media
 
PDF
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
PPT
Plunging Into Perl While Avoiding the Deep End (mostly)
Roy Zimmer
 
PDF
Introduction to Perl
worr1244
 
PPT
Cleancode
hendrikvb
 
PPT
Introduction to Perl
NBACriteria2SICET
 
PPTX
Perl slid
pacatarpit
 
PPT
Basic PHP
Todd Barber
 
PPT
PHP MySQL
Md. Sirajus Salayhin
 
PPT
Javascript
vikram singh
 
PPT
Php Crash Course
mussawir20
 
PDF
perltut
tutorialsruby
 
PDF
perltut
tutorialsruby
 
ODP
Php Learning show
Gnugroup India
 
PPT
The JavaScript Programming Language
Raghavan Mohan
 
PPT
The Java Script Programming Language
zone
 
Introduction to Perl - Day 1
Dave Cross
 
Perl Presentation
Sopan Shewale
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
 
CGI With Object Oriented Perl
Bunty Ray
 
Dealing with Legacy Perl Code - Peter Scott
O'Reilly Media
 
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
Plunging Into Perl While Avoiding the Deep End (mostly)
Roy Zimmer
 
Introduction to Perl
worr1244
 
Cleancode
hendrikvb
 
Introduction to Perl
NBACriteria2SICET
 
Perl slid
pacatarpit
 
Basic PHP
Todd Barber
 
Javascript
vikram singh
 
Php Crash Course
mussawir20
 
perltut
tutorialsruby
 
perltut
tutorialsruby
 
Php Learning show
Gnugroup India
 
The JavaScript Programming Language
Raghavan Mohan
 
The Java Script Programming Language
zone
 
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
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
 
ODP
Database Programming with Perl and DBIx::Class
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
 
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
 
Database Programming with Perl and DBIx::Class
Dave Cross
 

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 

Beginning Perl