Suche senden
Hochladen
Introduction to Perl
•
Als ODP, PDF herunterladen
•
9 gefällt mir
•
3,259 views
Dave Cross
Folgen
Slides from the Introduction to Perl course, November 2009.
Weniger lesen
Mehr lesen
Technologie
Business
Diashow-Anzeige
Melden
Teilen
Diashow-Anzeige
Melden
Teilen
1 von 152
Jetzt herunterladen
Empfohlen
LPW: Beginners Perl
LPW: Beginners Perl
Dave Cross
Perl Introduction
Perl Introduction
Marcos Rebelo
Perl programming language
Perl programming language
Elie Obeid
Perl Programming - 01 Basic Perl
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
Perl Scripting
Perl Scripting
Varadharajan Mukundan
Json
Json
Sabarinath Gnanasekar
Implementation Of String Functions In C
Implementation Of String Functions In C
Fazila Sadia
Python programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
Empfohlen
LPW: Beginners Perl
LPW: Beginners Perl
Dave Cross
Perl Introduction
Perl Introduction
Marcos Rebelo
Perl programming language
Perl programming language
Elie Obeid
Perl Programming - 01 Basic Perl
Perl Programming - 01 Basic Perl
Danairat Thanabodithammachari
Perl Scripting
Perl Scripting
Varadharajan Mukundan
Json
Json
Sabarinath Gnanasekar
Implementation Of String Functions In C
Implementation Of String Functions In C
Fazila Sadia
Python programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
Arrays in PHP
Arrays in PHP
Compare Infobase Limited
4.2 PHP Function
4.2 PHP Function
Jalpesh Vasa
PHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
10分で分かるRパッケージの作り方
10分で分かるRパッケージの作り方
Yohei Sato
String c
String c
thirumalaikumar3
Compiler Design Unit 2
Compiler Design Unit 2
Jena Catherine Bel D
Es6 to es5
Es6 to es5
Shakhzod Tojiyev
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
Functions in php
Functions in php
Kamal Acharya
Escape sequences
Escape sequences
Way2itech
PHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
Database Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
Perl tutorial
Perl tutorial
Manav Prasad
Core Java Equals and hash code
Core Java Equals and hash code
mhtspvtltd
Php array
Php array
Nikul Shah
C++ string
C++ string
Dheenadayalan18
Php basics
Php basics
Jamshid Hashimi
Php string function
Php string function
Ravi Bhadauria
Dynamic memory allocation
Dynamic memory allocation
Naveen Gupta
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
Beginning Perl
Beginning Perl
Dave Cross
Weitere ähnliche Inhalte
Was ist angesagt?
Arrays in PHP
Arrays in PHP
Compare Infobase Limited
4.2 PHP Function
4.2 PHP Function
Jalpesh Vasa
PHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
Vibrant Technologies & Computers
10分で分かるRパッケージの作り方
10分で分かるRパッケージの作り方
Yohei Sato
String c
String c
thirumalaikumar3
Compiler Design Unit 2
Compiler Design Unit 2
Jena Catherine Bel D
Es6 to es5
Es6 to es5
Shakhzod Tojiyev
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
P3 InfoTech Solutions Pvt. Ltd.
Functions in php
Functions in php
Kamal Acharya
Escape sequences
Escape sequences
Way2itech
PHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Glenn Guden
Database Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
Perl tutorial
Perl tutorial
Manav Prasad
Core Java Equals and hash code
Core Java Equals and hash code
mhtspvtltd
Php array
Php array
Nikul Shah
C++ string
C++ string
Dheenadayalan18
Php basics
Php basics
Jamshid Hashimi
Php string function
Php string function
Ravi Bhadauria
Dynamic memory allocation
Dynamic memory allocation
Naveen Gupta
Was ist angesagt?
(20)
Arrays in PHP
Arrays in PHP
4.2 PHP Function
4.2 PHP Function
PHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
10分で分かるRパッケージの作り方
10分で分かるRパッケージの作り方
String c
String c
Compiler Design Unit 2
Compiler Design Unit 2
Es6 to es5
Es6 to es5
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
Functions in php
Functions in php
Escape sequences
Escape sequences
PHP Functions & Arrays
PHP Functions & Arrays
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
Database Connectivity in PHP
Database Connectivity in PHP
Perl tutorial
Perl tutorial
Core Java Equals and hash code
Core Java Equals and hash code
Php array
Php array
C++ string
C++ string
Php basics
Php basics
Php string function
Php string function
Dynamic memory allocation
Dynamic memory allocation
Ähnlich wie Introduction to Perl
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
Beginning Perl
Beginning Perl
Dave Cross
Perl Presentation
Perl Presentation
Sopan Shewale
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Roy Zimmer
Introduction to Perl - Day 2
Introduction to Perl - Day 2
Dave Cross
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian Macali
Introduction to Modern Perl
Introduction to Modern Perl
Dave Cross
Intermediate Perl
Intermediate Perl
Dave Cross
Introduction to Perl
Introduction to Perl
worr1244
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
Mohammed Farrag
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
Roy Zimmer
P H P Part I, By Kian
P H P Part I, By Kian
phelios
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
Qrembiezs Intruder
Introduction to Perl
Introduction to Perl
NBACriteria2SICET
Php2
Php2
Keennary Pungyera
CGI With Object Oriented Perl
CGI With Object Oriented Perl
Bunty Ray
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
O'Reilly Media
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
Advanced Perl Techniques
Advanced Perl Techniques
Dave Cross
Modern Perl
Modern Perl
Marcos Rebelo
Ähnlich wie Introduction to Perl
(20)
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Beginning Perl
Beginning Perl
Perl Presentation
Perl Presentation
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Introduction to Perl - Day 2
Introduction to Perl - Day 2
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Introduction to Modern Perl
Introduction to Modern Perl
Intermediate Perl
Intermediate Perl
Introduction to Perl
Introduction to Perl
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
Plunging Into Perl While Avoiding the Deep End (mostly)
Plunging Into Perl While Avoiding the Deep End (mostly)
P H P Part I, By Kian
P H P Part I, By Kian
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
Introduction to Perl
Introduction to Perl
Php2
Php2
CGI With Object Oriented Perl
CGI With Object Oriented Perl
Dealing with Legacy Perl Code - Peter Scott
Dealing with Legacy Perl Code - Peter Scott
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Advanced Perl Techniques
Advanced Perl Techniques
Modern Perl
Modern Perl
Mehr von Dave Cross
Measuring the Quality of Your Perl Code
Measuring the Quality of Your Perl Code
Dave Cross
Apollo 11 at 50 - A Simple Twitter Bot
Apollo 11 at 50 - A Simple Twitter Bot
Dave Cross
Monoliths, Balls of Mud and Silver Bullets
Monoliths, Balls of Mud and Silver Bullets
Dave Cross
The Professional Programmer
The Professional Programmer
Dave Cross
I'm A Republic (Honest!)
I'm A Republic (Honest!)
Dave Cross
Web Site Tune-Up - Improve Your Googlejuice
Web Site Tune-Up - Improve Your Googlejuice
Dave Cross
Modern Perl Web Development with Dancer
Modern Perl Web Development with Dancer
Dave Cross
Freeing Tower Bridge
Freeing Tower Bridge
Dave Cross
Modern Perl Catch-Up
Modern Perl Catch-Up
Dave Cross
Error(s) Free Programming
Error(s) Free Programming
Dave Cross
Medium Perl
Medium Perl
Dave Cross
Modern Web Development with Perl
Modern Web Development with Perl
Dave Cross
Improving Dev Assistant
Improving Dev Assistant
Dave Cross
Conference Driven Publishing
Conference Driven Publishing
Dave Cross
Conference Driven Publishing
Conference Driven Publishing
Dave Cross
TwittElection
TwittElection
Dave Cross
Perl in the Internet of Things
Perl in the Internet of Things
Dave Cross
Return to the Kingdom of the Blind
Return to the Kingdom of the Blind
Dave Cross
Github, Travis-CI and Perl
Github, Travis-CI and Perl
Dave Cross
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
Dave Cross
Mehr von Dave Cross
(20)
Measuring the Quality of Your Perl Code
Measuring the Quality of Your Perl Code
Apollo 11 at 50 - A Simple Twitter Bot
Apollo 11 at 50 - A Simple Twitter Bot
Monoliths, Balls of Mud and Silver Bullets
Monoliths, Balls of Mud and Silver Bullets
The Professional Programmer
The Professional Programmer
I'm A Republic (Honest!)
I'm A Republic (Honest!)
Web Site Tune-Up - Improve Your Googlejuice
Web Site Tune-Up - Improve Your Googlejuice
Modern Perl Web Development with Dancer
Modern Perl Web Development with Dancer
Freeing Tower Bridge
Freeing Tower Bridge
Modern Perl Catch-Up
Modern Perl Catch-Up
Error(s) Free Programming
Error(s) Free Programming
Medium Perl
Medium Perl
Modern Web Development with Perl
Modern Web Development with Perl
Improving Dev Assistant
Improving Dev Assistant
Conference Driven Publishing
Conference Driven Publishing
Conference Driven Publishing
Conference Driven Publishing
TwittElection
TwittElection
Perl in the Internet of Things
Perl in the Internet of Things
Return to the Kingdom of the Blind
Return to the Kingdom of the Blind
Github, Travis-CI and Perl
Github, Travis-CI and Perl
Object-Oriented Programming with Perl and Moose
Object-Oriented Programming with Perl and Moose
Kürzlich hochgeladen
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
ThousandEyes
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
Radu Cotescu
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
BookNet Canada
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
Sinan KOZAK
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
Gabriella Davis
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Drew Madelung
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
HostedbyConfluent
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
Delhi Call girls
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
gurkirankumar98700
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Ridwan Fadjar
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
Anna Loughnan Colquhoun
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
Delhi Call girls
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
hans926745
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
Delhi Call girls
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
Sujit Pal
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Igalia
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
Pooja Nehwal
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
Michael W. Hawkins
Kürzlich hochgeladen
(20)
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
Introduction to Perl
1.
Introduction to Perl
Dave Cross Magnum Solutions Ltd [email_address]
2.
3.
Creating and running
a Perl program
4.
Getting help
5.
Input and Output
6.
Perl variables
7.
Operators and Functions
8.
9.
Subroutines
10.
Regular Expressions
11.
Smart Matching
12.
Finding and using
Modules
13.
14.
11:15 – Coffee
break (15 mins)
15.
13:00 – Lunch
(60 mins)
16.
14:00 – Begin
17.
15:30 – Coffee
break (15 mins)
18.
17:00 – End
19.
20.
What is Perl?
21.
22.
Pathologically Eclectic Rubbish
Lister
23.
“Perl” is the
language
24.
“perl” is the
compiler
25.
Never “PERL”
26.
27.
System administration tasks
28.
CGI and web
programming
29.
Database interaction
30.
Other Internet programming
31.
32.
NASA
33.
34.
Free (open source)
35.
Fast
36.
Flexible
37.
Secure
38.
Fun
39.
40.
41.
Impatience
42.
43.
Creating and Running
a Perl Program
44.
45.
print "Hello world";
46.
Put this in
a file called hello.pl
47.
48.
$ perl hello.pl
49.
50.
#!/usr/bin/perl
51.
Make program executable
52.
$ chmod +x
hello.pl
53.
Run from command
line
54.
$ ./hello.pl
55.
56.
Start with a
hash (#)
57.
Continue to end
of line
58.
# This is
a hello world program print "Hello, world!"; # print
59.
60.
For example, -w
turns on warnings
61.
Use on command
line
62.
perl -w hello.pl
63.
Or on shebang
line
64.
#!/usr/bin/perl -w
65.
More usually
use warnings
66.
Getting Help
67.
68.
Accessed through the
perldoc command
69.
perldoc perl
70.
perldoc perltoc
– table of contents
71.
Also online at
http://perldoc.perl.org/
72.
Lots of references
through the course
73.
74.
perldata
75.
perlsyn
76.
perlfaq
77.
perlstyle
78.
perlcheat
79.
Many many more
80.
Perl Variables
81.
82.
83.
To retrieve the
data stored in it
84.
85.
User variable names
may not start with numbers
86.
Variable names are
preceded by a punctuation mark indicating the type of data
87.
88.
Array variables start
with @
89.
90.
91.
92.
93.
use strict; my
$var;
94.
95.
my $name =
"Arthur";
96.
my $whoami =
'Just Another Perl Hacker';
97.
my $meaning_of_life =
42;
98.
my $number_less_than_1 =
0.000001;
99.
my $very_large_number =
3.27e17; # 3.27 times 10 to the power of 17
100.
101.
Add int to
a floating point number
102.
my $sum =
$meaning_of_life + $number_less_than_1;
103.
Putting a number
into a string
104.
print "$name says,
'The meaning of life is $sum.'";
105.
106.
my $price =
'$9.95';
107.
Double quotes do
108.
my $invline =
"24 widgets @ $price each";
109.
110.
print "He said
amp;quot;The price is 300amp;quot;";
111.
This can look
ugly
112.
113.
print qq(He said
"The price is 300");
114.
Also works for
single quotes
115.
print q(He said
"That's too expensive");
116.
117.
Test for it
with defined() function
118.
if (defined($my_var)) {
... }
119.
120.
my @fruit =
('apples', 'oranges', 'guavas', 'passionfruit', 'grapes');
121.
my @magic_numbers =
(23, 42, 69);
122.
my @random_scalars =
('mumble', 123.45, 'dave cross', -300, $name);
123.
124.
print $fruits[0]; #
prints "apples"
125.
Note: Indexes start
from zero
126.
print $random_scalars[2]; #
prints "dave cross"
127.
Note use of
$ as individual element of an array is a scalar
128.
129.
print @fruits[0,2,4]; #
prints "apples", "guavas", # "grapes"
130.
print @fruits[1 ..
3]; # prints "oranges", "guavas", # "passionfruit"
131.
Note use of
@ as we are accessing more than one element of the array
132.
133.
$array[400] = 'something
else';
134.
Also with slices
135.
@array[4, 7 ..
9] = ('four','seven', 'eight','nine');
136.
@array[1, 2] =
@array[2, 1];
137.
138.
139.
Therefore $#array
+ 1 is the number of elements
140.
$count = @array;
141.
Does the same
thing and is easier to understand
142.
143.
Initialised with a
list
144.
%french = ('one',
'un', 'two', 'deux', 'three', 'trois');
145.
146.
%german = (one
=> 'ein', two => 'zwei', three => 'drei');
147.
148.
print $german{two};
149.
As with arrays,
notice the use of $ to indicate that we're accessing a single value
150.
151.
Returns a list
of elements from a hash
152.
print @french{'one','two','three'}; #
prints "un", "deux" & "trois"
153.
Again, note use
of @ as we are accessing more than one value from the hash
154.
155.
$hash{bar} = 'something
else';
156.
Also with slices
157.
@hash{'foo', 'bar'} =
('something', 'else');
158.
@hash{'foo', 'bar'} =
@hash{'bar', 'foo'};
159.
160.
There is no
equivalent to $#array
161.
print %hash
is unhelpful
162.
We'll see ways
round these restrictions later
163.
164.
Many of them
have punctuation marks as names
165.
Others have names
in ALL_CAPS
166.
They are documented
in perlvar
167.
168.
print; # prints
the value of $_
169.
If a piece
of Perl code seems to be missing a variable, then it's probably using $_
170.
Think of “it”
or “that” in English
171.
172.
Three uses of
$_
173.
174.
Contains your programs
command line arguments
175.
my $num =
@ARGV; print "$num arguments: @ARGV";
176.
perl printargs.pl foo
bar baz
177.
178.
Contains the environment
variables that your script has access to.
179.
Keys are the
variable names
180.
Values are the…
well… values!
181.
print $ENV{PATH};
182.
Input and Output
183.
184.
We'll see more
input and output methods later in the day
185.
But here are
some simple methods
186.
187.
print “Hello world”;
188.
189.
$input = <STDIN>;
190.
< ... >
is the “read from filehandle” operator
191.
STDIN is the
standard input filehandle
192.
193.
Operators and Functions
194.
195.
“Things” that do
“stuff”
196.
Routines built into
Perl to manipulate data
197.
198.
199.
Less standard operations
modulus (%), exponentiation (**)
200.
$speed = $distance
/ $time;
201.
$vol = $length
* $breadth * $height;
202.
$area = $pi
* ($radius ** 2);
203.
$odd = $number
% 2;
204.
205.
$total = $total
+ $amount;
206.
Can be abbreviated
to
207.
$total += $amount;
208.
Even shorter
209.
$x++; # same
as $x += 1 or $x = $x + 1 $y--; # same as $y -= 1 or $y = $y - 1
210.
Subtle difference between
$x++ and ++$x
211.
212.
$name = $firstname
. ' ' $surname;
213.
Repetition (x)
214.
$line = '-'
x 80; $police = 'hello ' x 3;
215.
Shortcut versions available
216.
$page .= $line;
# $page = $page . $line
217.
$thing x= $i;
# $thing = $thing x $i
218.
219.
-e $file
does the file exist
220.
-r $file
is the file readable
221.
-w $file
is the file writeable
222.
223.
-d $file
is the file a directory
224.
-f $file
is the file a normal file
225.
-T $file
is a text file
226.
-B $file
is a binary file
227.
228.
Can take more
arguments than operators
229.
Arguments follow the
function name
230.
See perlfunc for
a complete list of Perl's built-in functions
231.
232.
$age = 29.75;
$years = int($age);
233.
@list = ('a',
'random', 'collection', 'of', 'words'); @sorted = sort(@list); # a collection of random words
234.
235.
$len = length
$a_string;
236.
uc and
lc return upper and lower case versions of a string
237.
$string = 'MiXeD
CaSe'; print "$string", uc $string, "", lc $string;
238.
See also
ucfirst and lcfirst
239.
240.
$word = 'word';
$letter = chop $word;
241.
chomp removes
the last character only if it is a newline and returns true or false appropriately
242.
243.
$string = 'Hello
world'; print substr($string, 0, 5); # prints 'Hello'
244.
You can also
assign to a substring
245.
substr($string, 0, 5)
= 'Greetings'; print $string; # prints 'Greetings world'
246.
247.
cos ,
sin , tan standard trigonometric functions
248.
exp exponentiation
using e
249.
log logarithm
to base e
250.
rand returns
a random number
251.
sqrt returns
the square root
252.
253.
push @array, $value;
254.
pop removes
and returns the last element in an array
255.
$value = pop
@array;
256.
shift and
unshift do the same for the start of an array
257.
258.
sort does
a lot more besides, see the docs (perldoc -f sort)
259.
reverse returns
a reversed list
260.
@reverse = reverse
@array;
261.
262.
@array = (1
.. 5); $string = join ', ', @array; # $string is '1, 2, 3, 4, 5'
263.
split takes
a string and converts it into an array
264.
$string = '1~2~3~4~5';
@array = split(/~/, $string); # @array is (1, 2, 3, 4, 5)
265.
266.
exists tells
you if an element exists in a hash
267.
keys returns
a list of all the keys in a hash
268.
values returns
a list of all the values in a hash
269.
270.
open(my $file, '<',
'in.dat');
271.
You can then
read the file with <$file>
272.
$line =
<$file>; # one line
273.
@lines = <$file>;
# all lines
274.
Finally, close the
file with close
275.
close($file);
276.
277.
$bytes = read(FILE,
$buffer, 1024);
278.
seek to
move to a random position in a file
279.
seek(FILE, 0, 0);
280.
281.
$where = tell
FILE;
282.
truncate to
truncate file to given size
283.
truncate FILE, $where;
284.
285.
open my $file,
'>', 'out.dat'; # overwrite
286.
open my $file,
'>>', 'out.dat'; # append
287.
Write to file
using print
288.
print $file “some
data”;
289.
Note lack of
comma
290.
291.
$now = time;
292.
localtime converts
that into more usable values
293.
($sec, $min, $hour,
$mday, $mon, $year, $wday, $yday, $isdst) = localtime($now);
294.
295.
$year is
years since 1900
296.
$wday is
0 (Sun) to 6 (Sat)
297.
298.
@time_bits = localtime(time);
299.
Call to time
can be omitted
300.
@time_bits = localtime;
301.
Use array slices
302.
($d, $m, $y)
= (localtime)[3 .. 5];
303.
304.
Easier to use
strftime (from POSIX.pm)
305.
use POSIX 'strftime';
306.
print strftime('%Y-%m-%d',
localtime);
307.
308.
309.
print strftime('%H:%M:%S',
localtime);
310.
Conditional Constructs
311.
312.
This makes for
far more interesting programs
313.
The unit of
program execution is a block of code
314.
Blocks are delimited
with braces { … }
315.
316.
But what is
truth?
317.
318.
0 (the number
zero)
319.
'' (the empty
string)
320.
undef (an undefined
value)
321.
() (an empty
list)
322.
Everything else is
true
323.
324.
325.
326.
$x >= $y
or $x ge $y
327.
328.
$x <= $y
or $x le $y
329.
330.
'0' == (3
* 2) - 6 # true
331.
'apple' gt 'banana'
# false
332.
'apple' == 'banana'
# true(!)
333.
1 + 2
== '3 bears' # true
334.
1 + 3
== 'three' # false
335.
336.
337.
Different precedence though
338.
339.
Only need to
evaluate EXPR_2 if EXPR_1 evaluates as false
340.
We can use
this to make code easier to follow
341.
open FILE, 'something.dat'
or die "Can't open file: $!";
342.
@ARGV == 2
or print $usage_msg;
343.
344.
if (EXPR) {
BLOCK }
345.
Only executes BLOCK
if EXPR is true
346.
if ($name eq
'Doctor') { regenerate(); }
347.
348.
if (EXPR) {
BLOCK1 } else { BLOCK2 }
349.
If EXPR is
true, execute BLOCK1, otherwise execute BLOCK2
350.
if ($name eq
'Doctor') { regenerate(); } else { die "Game over!"; }
351.
352.
if (EXPR1) {
BLOCK1 } elsif (EXPR2) { BLOCK2 } else { BLOCK3 }
353.
354.
355.
if ($name eq
'Doctor') { regenerate(); } elsif ($tardis_location eq $here) { escape(); } else { die "Game over!"; }
356.
357.
while (EXPR) {
BLOCK }
358.
Repeat BLOCK while
EXPR is true
359.
while ($dalek_prisoners) {
print "Ex-ter-min-ate"; $dalek_prisoners--; }
360.
361.
until (EXPR) {
BLOCK }
362.
Execute BLOCK until
EXPR is true
363.
until ($regenerations ==
12) { print "Regenerating"; regenerate(); $regenerations++; }
364.
365.
for (INIT; EXPR;
INCR) { BLOCK }
366.
Like C
367.
Execute INIT If
EXPR is false, exit loop, otherwise execute BLOCK, execute INCR and retest EXPR
368.
369.
for ($i =
1; $i <= 10; $i++) { print "$i squared is ", $i * $i, ""; }
370.
Used surprisingly rarely
371.
372.
foreach VAR (LIST)
{ BLOCK }
373.
For each element
of LIST, set VAR to equal the element and execute BLOCK
374.
foreach $i (1
.. 10) { print "$i squared is ", $i * $i, ""; }
375.
376.
my %months =
(Jan => 31, Feb => 28, Mar => 31, Apr => 30, May => 31, Jun => 30, … ); foreach (keys %months) { print "$_ has $months{$_} days"; }
377.
378.
while (<STDIN>) {
print; }
379.
This is the
same as
380.
while (defined($_ =
<STDIN>)) { print $_; }
381.
382.
last –
jump out of loop
383.
redo –
jump to start of same iteration of loop
384.
Subroutines
385.
386.
Make it easy
to repeat code
387.
Subroutines have a
name and a block of code
388.
sub NAME {
BLOCK }
389.
390.
391.
exterminate();
392.
exterminate;
393.
last one only
works if function has been predeclared
394.
395.
exterminate('The Doctor');
396.
Arguments end up
in the @_ array within the function
397.
398.
399.
sub exterminate {
foreach (@_) { print "Ex-Ter-Min-Ate $_"; $timelords--; } }
400.
401.
&my_sub passes
on the contents of @_ to the called subroutine
402.
sub first {
&second }; sub second { print @_ }; first('some', 'random', 'data');
403.
You usually don't
want to do that
404.
405.
Passing by reference
passes the actual variable. Changing the argument alters the external value
406.
Perl allows you
to choose
407.
408.
my ($arg1, $arg2)
= @_;
409.
Updating $arg1
and $arg2 doesn’t effect anything outside the subroutine
410.
411.
$_[0] = 'whatever';
412.
Updating the contents
of @_ updates the external values
413.
414.
sub exterminate {
if (rand > .25) { print "Ex-Ter-Min-Ate $_[0]"; $timelords--; return 1; } else { return; } }
415.
416.
sub exterminate {
my @exterminated; foreach (@_) { if (rand > .25) { print "Ex-Ter-Min-Ate $_"; $timelords--; push @exterminated, $_; } } return @exterminated; }
417.
Regular Expressions
418.
419.
A bit like
wild-cards
420.
421.
Sometimes overused!
422.
Documented in perldoc
perlre
423.
424.
Works on
$_ by default
425.
In scalar context
returns true if the match succeeds
426.
In list context
returns list of "captured" text
427.
m is optional
if you use / characters
428.
With m you
can use any delimiters
429.
430.
431.
Works on
$_ by default
432.
In scalar context
returns true if substitution succeeds
433.
In list context
returns number of replacements
434.
Can choose any
delimiter
435.
436.
437.
$name =~ s/Dave/David/;
438.
439.
^ -
matches start of string
440.
$ -
matches end of string
441.
. -
matches any character (except )
442.
-
matches a whitespace character
443.
-
matches a non-whitespace character
444.
445.
-
matches any non-digit
446.
-
matches any "word" character
447.
-
matches any "non-word" character
448.
-
matches a word boundary
449.
-
matches anywhere except a word boundary
450.
451.
452.
? -
match zero or one
453.
* -
match zero or more
454.
+ -
match one or more
455.
{n} -
match exactly n
456.
{n,} -
match n or more
457.
{n,m} -
match between n and m
458.
459.
460.
/[aeiou]/ # match
any vowel
461.
Use - to
define a contiguous range
462.
/[A-Z]/ # match
upper case letters
463.
Use ^ to
match inverse set
464.
/[^A-Za-z] # match
non-letters
465.
466.
/rose|martha|donna/i;
467.
Use parentheses for
grouping
468.
/^(rose|martha|donna)$/i;
469.
470.
The captured parts
are in $1 , $2 , etc…
471.
while (<FILE>) {
if (/^(+)+(+)/) { print "The first word was $1"; print "The second word was $2"; } }
472.
473.
my @nums =
$text =~ /(+)/g; print "I found these integers:"; print "@nums";
474.
475.
perldoc perlretut
476.
Mastering Regular Expressions
– Jeffrey Freidl
477.
Smart Matching
478.
479.
Powerful matching operator
480.
DWIM
481.
Examines operands
482.
Decides which match
to apply
483.
484.
New operator
485.
Looks a bit
like the binding operator ( =~ )
486.
Can be used
in place of it
487.
$some_text =~ /some
regex/
488.
Can be replaced
with
489.
$some_text ~~ /some
regex/
490.
491.
~~ does
a regex match
492.
Cleverer than that
though
493.
%hash ~~ /regex/
494.
Regex match on
hash keys
495.
@array ~~ /regex/
496.
Regex match on
array elements
497.
498.
Checks that arrays
are the same
499.
$scalar ~~ @array
500.
Checks scalar exists
in array
501.
$scalar ~~ %hash
502.
Checks scalar is
a hash key
503.
504.
$scalar1 ~~ $scalar2
505.
It depends
506.
If both look
like numbers
507.
~~ acts
like ==
508.
Otherwise
509.
~~ acts
like eq
510.
Finding and Using
Modules
511.
512.
Perl comes with
over 100 modules (see “perldoc perlmodlib” for list)
513.
514.
http://search.cpan.org
515.
516.
517.
distribution name
518.
519.
520.
521.
522.
You can have
your own personal module library
523.
524.
525.
Automatically carries out
installation process
526.
Can also handle
required modules
527.
528.
529.
530.
Or
531.
cpanp -i Some::Module
532.
533.
Object modules usually
don't
534.
Difference not clear
cut (e.g. CGI.pm)
535.
536.
use My::Module;
537.
Import optional components:
538.
use My::Module qw(my_sub
@my_arr);
539.
540.
use My:Module qw(:advanced);
541.
Use imported components:
542.
$data = my_sub(@my_arr);
543.
544.
use My::Object;
545.
Create an object:
546.
547.
$obj->set_name($name);
548.
549.
Time::Local
550.
Text::ParseWords
551.
Getopt::Std
552.
Cwd
553.
554.
POSIX
555.
CGI
556.
Carp
557.
Benchmark
558.
Data::Dumper
559.
560.
DBI
561.
DBIx::Class
562.
DateTime
563.
HTML::Parser
564.
565.
WWW::Mechanize
566.
Email::Simple
567.
XML::LibXML
568.
XML::Feed
569.
Moose
570.
Jetzt herunterladen