0
Introduction to Perl Dave Cross Magnum Solutions Ltd [email_address]
What We Will Cover <ul><li>What is Perl?
Creating and running a Perl program
Getting help
Input and Output
Perl variables
Operators and Functions </li></ul>
What We Will Cover <ul><li>Conditional Constructs
Subroutines
Regular Expressions
Smart Matching
Finding and using Modules </li></ul>
Schedule <ul><li>09:45 – Begin
11:15 – Coffee break (15 mins)
13:00 – Lunch (60 mins)
14:00 – Begin
15:30 – Coffee break (15 mins)
17:00 – End </li></ul>
Resources <ul><li>Slides available on-line </li><ul><li>http://mag-sol.com/train/public/2009-11/ukuug </li></ul><li>Also s...
What is Perl?
Perl's Name <ul><li>Practical Extraction and Reporting Language
Pathologically Eclectic Rubbish Lister
“Perl” is the language
“perl” is the compiler
Never “PERL” </li></ul>
Typical Uses of Perl <ul><li>Text processing
System administration tasks
CGI and web programming
Database interaction
Other Internet programming </li></ul>
Less Typical Uses of Perl <ul><li>Human Genome Project
NASA </li></ul>
What is Perl Like? <ul><li>General purpose programming language
Free (open source)‏
Fast
Flexible
Secure
Fun </li></ul>
The Perl Philosophy <ul><li>There's more than one way to do it
Three virtues of a programmer </li><ul><li>Laziness
Impatience
Hubris </li></ul><li>Share and enjoy! </li></ul>
Creating and Running a Perl Program
Creating a Perl Program <ul><li>Our first Perl program
print &quot;Hello world
&quot;;
Put this in a file called hello.pl </li></ul>
Running a Perl Program <ul><li>Running a Perl program from the command line
$ perl hello.pl </li></ul>
Running a Perl Program <ul><li>The &quot;shebang&quot; line (Unix, not Perl)
#!/usr/bin/perl
Make program executable
$ chmod +x hello.pl
Run from command line
$ ./hello.pl </li></ul>
Perl Comments <ul><li>Add comments to your code
Start with a hash (#)‏
Continue to end of line
# This is a hello world program print &quot;Hello, world!
&quot;; # print  </li></ul>
Command Line Options <ul><li>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
More usually  use warnings </li></ul>
Getting Help
Perl Documentation <ul><li>Perl comes with a huge amount of documentation
Accessed through the  perldoc  command
perldoc perl
perldoc perltoc  – table of contents
Also online at http://perldoc.perl.org/
Lots of references through the course </li></ul>
Some Useful Pages <ul><li>perlintro
perldata
perlsyn
perlfaq
perlstyle
perlcheat
Many many more </li></ul>
Perl Variables
What is a Variable? <ul><li>A place where we can store data
A variable needs a name </li><ul><li>To put new data in it
To retrieve the data stored in it </li></ul></ul>
Variable Names <ul><li>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 </li></ul>
Types of Perl Variable <ul><li>Different types of variables start with a different symbol </li><ul><li>Scalar variables st...
Array variables start with @
Hash variables start with % </li></ul><li>More on these types soon </li></ul>
Declaring Variables <ul><li>You don't need to declare variables in Perl
But it's a very good idea </li><ul><li>typos
scoping </li></ul><li>Using the  strict  pragma
use strict; my $var; </li></ul>
Scalar Variables <ul><li>Store a single item of data
my $name = &quot;Arthur&quot;;
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 </li></ul>
Type Conversions <ul><li>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 &quot;$name says, 'The meaning of life is $sum.'
&quot;; </li></ul>
Quoting Strings <ul><li>Single quotes don't expand variables or escape sequences
my $price = '$9.95';
Double quotes do
my $invline =   &quot;24 widgets @ $price each
&quot;; </li></ul>
Backslashes <ul><li>Use a backslash to escape special characters in double quoted strings
print &quot;He said &quot;The price is  $300&quot;&quot;;
This can look ugly </li></ul>
Better Quotes <ul><li>This is a tidier alternative
print qq(He said &quot;The price is $300&quot;);
Also works for single quotes
print q(He said &quot;That's too expensive&quot;); </li></ul>
Undefined Values <ul><li>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)) { ... } </li></ul>
Array Variables <ul><li>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); </li></ul>
Array Elements <ul><li>Accessing individual elements of an array
print $fruits[0]; # prints &quot;apples&quot;
Note: Indexes start from zero
print $random_scalars[2]; # prints &quot;dave cross&quot;
Note use of $ as individual element of an array is a scalar </li></ul>
Array Slices <ul><li>Returns a list of elements from an array
print @fruits[0,2,4]; # prints &quot;apples&quot;, &quot;guavas&quot;, # &quot;grapes&quot;
print @fruits[1 .. 3]; # prints &quot;oranges&quot;, &quot;guavas&quot;, # &quot;passionfruit&quot;
Note use of @ as we are accessing more than one element of the array  </li></ul>
Setting Array Values <ul><li>$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 </li><ul><li>($x, $y) = ($y, $x); </li></ul></ul>
Array Size <ul><li>$#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 </li></ul>
Hash Variables <ul><li>Hashes implement “look-up tables” or “dictionaries”
Initialised with a list
%french = ('one', 'un',   'two', 'deux',   'three', 'trois'); </li></ul>
Fat Comma <ul><li>The  “fat comma” (=>) is easier to understand
%german = (one  => 'ein',   two  => 'zwei',    three => 'drei'); </li></ul>
Accessing Hash Values <ul><li>$three = $french{three};
print $german{two};
As with arrays, notice the use of $ to indicate that we're accessing a single value </li></ul>
Hash Slices <ul><li>Just like array slices
Returns a list of elements from a hash
print @french{'one','two','three'}; # prints &quot;un&quot;, &quot;deux&quot; & &quot;trois&quot;
Upcoming SlideShare
Loading in...5
×

Introduction to Perl

6,271

Published on

Slides from the Introduction to Perl course, November 2009.

Published in: Technology, Business
0 Comments
10 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
6,271
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
508
Comments
0
Likes
10
Embeds 0
No embeds

No notes for slide

Transcript of "Introduction to Perl"

  1. 1. Introduction to Perl Dave Cross Magnum Solutions Ltd [email_address]
  2. 2. What We Will Cover <ul><li>What is Perl?
  3. 3. Creating and running a Perl program
  4. 4. Getting help
  5. 5. Input and Output
  6. 6. Perl variables
  7. 7. Operators and Functions </li></ul>
  8. 8. What We Will Cover <ul><li>Conditional Constructs
  9. 9. Subroutines
  10. 10. Regular Expressions
  11. 11. Smart Matching
  12. 12. Finding and using Modules </li></ul>
  13. 13. Schedule <ul><li>09:45 – Begin
  14. 14. 11:15 – Coffee break (15 mins)
  15. 15. 13:00 – Lunch (60 mins)
  16. 16. 14:00 – Begin
  17. 17. 15:30 – Coffee break (15 mins)
  18. 18. 17:00 – End </li></ul>
  19. 19. Resources <ul><li>Slides available on-line </li><ul><li>http://mag-sol.com/train/public/2009-11/ukuug </li></ul><li>Also see Slideshare </li><ul><li>http://www.slideshare.net/davorg/slideshows </li></ul><li>Get Satisfaction </li><ul><li>http://getsatisfaction.com/magnum </li></ul></ul>
  20. 20. What is Perl?
  21. 21. Perl's Name <ul><li>Practical Extraction and Reporting Language
  22. 22. Pathologically Eclectic Rubbish Lister
  23. 23. “Perl” is the language
  24. 24. “perl” is the compiler
  25. 25. Never “PERL” </li></ul>
  26. 26. Typical Uses of Perl <ul><li>Text processing
  27. 27. System administration tasks
  28. 28. CGI and web programming
  29. 29. Database interaction
  30. 30. Other Internet programming </li></ul>
  31. 31. Less Typical Uses of Perl <ul><li>Human Genome Project
  32. 32. NASA </li></ul>
  33. 33. What is Perl Like? <ul><li>General purpose programming language
  34. 34. Free (open source)‏
  35. 35. Fast
  36. 36. Flexible
  37. 37. Secure
  38. 38. Fun </li></ul>
  39. 39. The Perl Philosophy <ul><li>There's more than one way to do it
  40. 40. Three virtues of a programmer </li><ul><li>Laziness
  41. 41. Impatience
  42. 42. Hubris </li></ul><li>Share and enjoy! </li></ul>
  43. 43. Creating and Running a Perl Program
  44. 44. Creating a Perl Program <ul><li>Our first Perl program
  45. 45. print &quot;Hello world &quot;;
  46. 46. Put this in a file called hello.pl </li></ul>
  47. 47. Running a Perl Program <ul><li>Running a Perl program from the command line
  48. 48. $ perl hello.pl </li></ul>
  49. 49. Running a Perl Program <ul><li>The &quot;shebang&quot; line (Unix, not Perl)
  50. 50. #!/usr/bin/perl
  51. 51. Make program executable
  52. 52. $ chmod +x hello.pl
  53. 53. Run from command line
  54. 54. $ ./hello.pl </li></ul>
  55. 55. Perl Comments <ul><li>Add comments to your code
  56. 56. Start with a hash (#)‏
  57. 57. Continue to end of line
  58. 58. # This is a hello world program print &quot;Hello, world! &quot;; # print </li></ul>
  59. 59. Command Line Options <ul><li>Options to control execution of the program
  60. 60. For example, -w turns on warnings
  61. 61. Use on command line
  62. 62. perl -w hello.pl
  63. 63. Or on shebang line
  64. 64. #!/usr/bin/perl -w
  65. 65. More usually use warnings </li></ul>
  66. 66. Getting Help
  67. 67. Perl Documentation <ul><li>Perl comes with a huge amount of documentation
  68. 68. Accessed through the perldoc command
  69. 69. perldoc perl
  70. 70. perldoc perltoc – table of contents
  71. 71. Also online at http://perldoc.perl.org/
  72. 72. Lots of references through the course </li></ul>
  73. 73. Some Useful Pages <ul><li>perlintro
  74. 74. perldata
  75. 75. perlsyn
  76. 76. perlfaq
  77. 77. perlstyle
  78. 78. perlcheat
  79. 79. Many many more </li></ul>
  80. 80. Perl Variables
  81. 81. What is a Variable? <ul><li>A place where we can store data
  82. 82. A variable needs a name </li><ul><li>To put new data in it
  83. 83. To retrieve the data stored in it </li></ul></ul>
  84. 84. Variable Names <ul><li>Contain alphanumeric characters and underscores
  85. 85. User variable names may not start with numbers
  86. 86. Variable names are preceded by a punctuation mark indicating the type of data </li></ul>
  87. 87. Types of Perl Variable <ul><li>Different types of variables start with a different symbol </li><ul><li>Scalar variables start with $
  88. 88. Array variables start with @
  89. 89. Hash variables start with % </li></ul><li>More on these types soon </li></ul>
  90. 90. Declaring Variables <ul><li>You don't need to declare variables in Perl
  91. 91. But it's a very good idea </li><ul><li>typos
  92. 92. scoping </li></ul><li>Using the strict pragma
  93. 93. use strict; my $var; </li></ul>
  94. 94. Scalar Variables <ul><li>Store a single item of data
  95. 95. my $name = &quot;Arthur&quot;;
  96. 96. my $whoami = 'Just Another Perl Hacker';
  97. 97. my $meaning_of_life = 42;
  98. 98. my $number_less_than_1 = 0.000001;
  99. 99. my $very_large_number = 3.27e17; # 3.27 times 10 to the power of 17 </li></ul>
  100. 100. Type Conversions <ul><li>Perl converts between strings and numbers whenever necessary
  101. 101. Add int to a floating point number
  102. 102. my $sum = $meaning_of_life + $number_less_than_1;
  103. 103. Putting a number into a string
  104. 104. print &quot;$name says, 'The meaning of life is $sum.' &quot;; </li></ul>
  105. 105. Quoting Strings <ul><li>Single quotes don't expand variables or escape sequences
  106. 106. my $price = '$9.95';
  107. 107. Double quotes do
  108. 108. my $invline = &quot;24 widgets @ $price each &quot;; </li></ul>
  109. 109. Backslashes <ul><li>Use a backslash to escape special characters in double quoted strings
  110. 110. print &quot;He said &quot;The price is $300&quot;&quot;;
  111. 111. This can look ugly </li></ul>
  112. 112. Better Quotes <ul><li>This is a tidier alternative
  113. 113. print qq(He said &quot;The price is $300&quot;);
  114. 114. Also works for single quotes
  115. 115. print q(He said &quot;That's too expensive&quot;); </li></ul>
  116. 116. Undefined Values <ul><li>A scalar variable that hasn't had data put into it will contain the special value “undef”
  117. 117. Test for it with defined() function
  118. 118. if (defined($my_var)) { ... } </li></ul>
  119. 119. Array Variables <ul><li>Arrays contain an ordered list of scalar values
  120. 120. my @fruit = ('apples', 'oranges', 'guavas', 'passionfruit', 'grapes');
  121. 121. my @magic_numbers = (23, 42, 69);
  122. 122. my @random_scalars = ('mumble', 123.45, 'dave cross', -300, $name); </li></ul>
  123. 123. Array Elements <ul><li>Accessing individual elements of an array
  124. 124. print $fruits[0]; # prints &quot;apples&quot;
  125. 125. Note: Indexes start from zero
  126. 126. print $random_scalars[2]; # prints &quot;dave cross&quot;
  127. 127. Note use of $ as individual element of an array is a scalar </li></ul>
  128. 128. Array Slices <ul><li>Returns a list of elements from an array
  129. 129. print @fruits[0,2,4]; # prints &quot;apples&quot;, &quot;guavas&quot;, # &quot;grapes&quot;
  130. 130. print @fruits[1 .. 3]; # prints &quot;oranges&quot;, &quot;guavas&quot;, # &quot;passionfruit&quot;
  131. 131. Note use of @ as we are accessing more than one element of the array </li></ul>
  132. 132. Setting Array Values <ul><li>$array[4] = 'something';
  133. 133. $array[400] = 'something else';
  134. 134. Also with slices
  135. 135. @array[4, 7 .. 9] = ('four','seven', 'eight','nine');
  136. 136. @array[1, 2] = @array[2, 1];
  137. 137. Doesn't need to be an array </li><ul><li>($x, $y) = ($y, $x); </li></ul></ul>
  138. 138. Array Size <ul><li>$#array is the index of the last element in @array
  139. 139. Therefore $#array + 1 is the number of elements
  140. 140. $count = @array;
  141. 141. Does the same thing and is easier to understand </li></ul>
  142. 142. Hash Variables <ul><li>Hashes implement “look-up tables” or “dictionaries”
  143. 143. Initialised with a list
  144. 144. %french = ('one', 'un', 'two', 'deux', 'three', 'trois'); </li></ul>
  145. 145. Fat Comma <ul><li>The “fat comma” (=>) is easier to understand
  146. 146. %german = (one => 'ein', two => 'zwei', three => 'drei'); </li></ul>
  147. 147. Accessing Hash Values <ul><li>$three = $french{three};
  148. 148. print $german{two};
  149. 149. As with arrays, notice the use of $ to indicate that we're accessing a single value </li></ul>
  150. 150. Hash Slices <ul><li>Just like array slices
  151. 151. Returns a list of elements from a hash
  152. 152. print @french{'one','two','three'}; # prints &quot;un&quot;, &quot;deux&quot; & &quot;trois&quot;
  153. 153. Again, note use of @ as we are accessing more than one value from the hash </li></ul>
  154. 154. Setting Hash Values <ul><li>$hash{foo} = 'something';
  155. 155. $hash{bar} = 'something else';
  156. 156. Also with slices
  157. 157. @hash{'foo', 'bar'} = ('something', 'else');
  158. 158. @hash{'foo', 'bar'} = @hash{'bar', 'foo'}; </li></ul>
  159. 159. More About Hashes <ul><li>Hashes are not sorted
  160. 160. There is no equivalent to $#array
  161. 161. print %hash is unhelpful
  162. 162. We'll see ways round these restrictions later </li></ul>
  163. 163. Special Perl Variables <ul><li>Perl has many special variables
  164. 164. Many of them have punctuation marks as names
  165. 165. Others have names in ALL_CAPS
  166. 166. They are documented in perlvar </li></ul>
  167. 167. The Default Variable <ul><li>Many Perl operations either set $_ or use its value if no other is given
  168. 168. print; # prints the value of $_
  169. 169. If a piece of Perl code seems to be missing a variable, then it's probably using $_
  170. 170. Think of “it” or “that” in English </li></ul>
  171. 171. Using $_ <ul><li>while (<FILE>) { if (/regex/) { print; } }
  172. 172. Three uses of $_ </li></ul>
  173. 173. A Special Array <ul><li>@ARGV
  174. 174. Contains your programs command line arguments
  175. 175. my $num = @ARGV; print &quot;$num arguments: @ARGV &quot;;
  176. 176. perl printargs.pl foo bar baz </li></ul>
  177. 177. A Special Hash <ul><li>%ENV
  178. 178. Contains the environment variables that your script has access to.
  179. 179. Keys are the variable names
  180. 180. Values are the… well… values!
  181. 181. print $ENV{PATH}; </li></ul>
  182. 182. Input and Output
  183. 183. Input and Output <ul><li>Programs become more useful with input and output
  184. 184. We'll see more input and output methods later in the day
  185. 185. But here are some simple methods </li></ul>
  186. 186. Output <ul><li>The easiest way to get data out of a Perl program is to use print
  187. 187. print “Hello world ”; </li></ul>
  188. 188. Input <ul><li>The easiest way to get data into a Perl program is to read from STDIN
  189. 189. $input = <STDIN>;
  190. 190. < ... > is the “read from filehandle” operator
  191. 191. STDIN is the standard input filehandle </li></ul>
  192. 192. A Complete Example <ul><li>#!/usr/bin/perl print 'What is your name: '; $name = <STDIN>; print “Hello $name”; </li></ul>
  193. 193. Operators and Functions
  194. 194. Operators and Functions <ul><li>What are operators and functions?
  195. 195. “Things” that do “stuff”
  196. 196. Routines built into Perl to manipulate data
  197. 197. Other languages have a strong distinction between operators and functions </li><ul><li>in Perl that distinction can be a bit blurred </li></ul><li>See perlop and perlfunc </li></ul>
  198. 198. Arithmetic Operators <ul><li>Standard arithmetic operations add (+), subtract (-), multiply (*), divide (/)‏
  199. 199. Less standard operations modulus (%), exponentiation (**)‏
  200. 200. $speed = $distance / $time;
  201. 201. $vol = $length * $breadth * $height;
  202. 202. $area = $pi * ($radius ** 2);
  203. 203. $odd = $number % 2; </li></ul>
  204. 204. Shortcut Operators <ul><li>Often need to do things like
  205. 205. $total = $total + $amount;
  206. 206. Can be abbreviated to
  207. 207. $total += $amount;
  208. 208. Even shorter
  209. 209. $x++; # same as $x += 1 or $x = $x + 1 $y--; # same as $y -= 1 or $y = $y - 1
  210. 210. Subtle difference between $x++ and ++$x </li></ul>
  211. 211. String Operators <ul><li>Concaternation (.)
  212. 212. $name = $firstname . ' ' $surname;
  213. 213. Repetition (x)
  214. 214. $line = '-' x 80; $police = 'hello ' x 3;
  215. 215. Shortcut versions available
  216. 216. $page .= $line; # $page = $page . $line
  217. 217. $thing x= $i; # $thing = $thing x $i </li></ul>
  218. 218. File Test Operators <ul><li>Check various attributes of a file
  219. 219. -e $file does the file exist
  220. 220. -r $file is the file readable
  221. 221. -w $file is the file writeable </li></ul>
  222. 222. More File Test Operators <ul><li>Check various attributes of a file
  223. 223. -d $file is the file a directory
  224. 224. -f $file is the file a normal file
  225. 225. -T $file is a text file
  226. 226. -B $file is a binary file </li></ul>
  227. 227. Functions <ul><li>Have longer names than operators
  228. 228. Can take more arguments than operators
  229. 229. Arguments follow the function name
  230. 230. See perlfunc for a complete list of Perl's built-in functions </li></ul>
  231. 231. Function Return Values <ul><li>Functions can return scalars or lists (or nothing)‏
  232. 232. $age = 29.75; $years = int($age);
  233. 233. @list = ('a', 'random', 'collection', 'of', 'words'); @sorted = sort(@list); # a collection of random words </li></ul>
  234. 234. String Functions <ul><li>length returns the length of a string
  235. 235. $len = length $a_string;
  236. 236. uc and lc return upper and lower case versions of a string
  237. 237. $string = 'MiXeD CaSe'; print &quot;$string &quot;, uc $string, &quot; &quot;, lc $string;
  238. 238. See also ucfirst and lcfirst </li></ul>
  239. 239. More String Functions <ul><li>chop removes the last character from a string and returns it
  240. 240. $word = 'word'; $letter = chop $word;
  241. 241. chomp removes the last character only if it is a newline and returns true or false appropriately </li></ul>
  242. 242. Substrings <ul><li>substr returns substrings from a string
  243. 243. $string = 'Hello world'; print substr($string, 0, 5); # prints 'Hello'
  244. 244. You can also assign to a substring
  245. 245. substr($string, 0, 5) = 'Greetings'; print $string; # prints 'Greetings world' </li></ul>
  246. 246. Numeric Functions <ul><li>abs returns the absolute value
  247. 247. cos , sin , tan standard trigonometric functions
  248. 248. exp exponentiation using e
  249. 249. log logarithm to base e
  250. 250. rand returns a random number
  251. 251. sqrt returns the square root </li></ul>
  252. 252. Array Manipulation <ul><li>push adds a new element to the end of an array
  253. 253. push @array, $value;
  254. 254. pop removes and returns the last element in an array
  255. 255. $value = pop @array;
  256. 256. shift and unshift do the same for the start of an array </li></ul>
  257. 257. Array Manipulation <ul><li>sort returns a sorted list </li><ul><li>it does not sort the list in place </li></ul><li>@sorted = sort @array;
  258. 258. sort does a lot more besides, see the docs (perldoc -f sort)‏
  259. 259. reverse returns a reversed list
  260. 260. @reverse = reverse @array; </li></ul>
  261. 261. Arrays and Strings <ul><li>join takes an array and returns a string
  262. 262. @array = (1 .. 5); $string = join ', ', @array; # $string is '1, 2, 3, 4, 5'
  263. 263. split takes a string and converts it into an array
  264. 264. $string = '1~2~3~4~5'; @array = split(/~/, $string); # @array is (1, 2, 3, 4, 5)‏ </li></ul>
  265. 265. Hash Functions <ul><li>delete removes a key/value pair from a hash
  266. 266. exists tells you if an element exists in a hash
  267. 267. keys returns a list of all the keys in a hash
  268. 268. values returns a list of all the values in a hash </li></ul>
  269. 269. File Operations <ul><li>open opens a file and associates it with a filehandle
  270. 270. open(my $file, '<', 'in.dat');
  271. 271. You can then read the file with <$file>
  272. 272. $line = <$file>; # one line
  273. 273. @lines = <$file>; # all lines
  274. 274. Finally, close the file with close
  275. 275. close($file); </li></ul>
  276. 276. Other File Functions <ul><li>read to read a fixed number of bytes into a buffer
  277. 277. $bytes = read(FILE, $buffer, 1024);
  278. 278. seek to move to a random position in a file
  279. 279. seek(FILE, 0, 0); </li></ul>
  280. 280. Other File Functions <ul><li>tell to get current file position
  281. 281. $where = tell FILE;
  282. 282. truncate to truncate file to given size
  283. 283. truncate FILE, $where; </li></ul>
  284. 284. Writing to Files <ul><li>Open file in write mode
  285. 285. open my $file, '>', 'out.dat'; # overwrite
  286. 286. open my $file, '>>', 'out.dat'; # append
  287. 287. Write to file using print
  288. 288. print $file “some data ”;
  289. 289. Note lack of comma </li></ul>
  290. 290. Time Functions <ul><li>time returns the number of seconds since midnight Jan 1st 1970
  291. 291. $now = time;
  292. 292. localtime converts that into more usable values
  293. 293. ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($now); </li></ul>
  294. 294. localtime Caveats <ul><li>$mon is 0 to 11
  295. 295. $year is years since 1900
  296. 296. $wday is 0 (Sun) to 6 (Sat)‏ </li></ul>
  297. 297. localtime Shortcuts <ul><li>It's common to use localtime on the current time
  298. 298. @time_bits = localtime(time);
  299. 299. Call to time can be omitted
  300. 300. @time_bits = localtime;
  301. 301. Use array slices
  302. 302. ($d, $m, $y) = (localtime)[3 .. 5]; </li></ul>
  303. 303. Date & Time Formats <ul><li>You can get formatted dates by fiddling the return values from localtime
  304. 304. Easier to use strftime (from POSIX.pm)
  305. 305. use POSIX 'strftime';
  306. 306. print strftime('%Y-%m-%d', localtime); </li></ul>
  307. 307. Date & Time Formats <ul><li>Format followed by list of date/time values
  308. 308. Format is POSIX standard </li><ul><li>Like UNIX date command </li></ul><li>print strftime('%d %B %y', localtime);
  309. 309. print strftime('%H:%M:%S', localtime); </li></ul>
  310. 310. Conditional Constructs
  311. 311. Conditional Constructs <ul><li>Conditional constructs allow us to choose different routes of execution through the program
  312. 312. This makes for far more interesting programs
  313. 313. The unit of program execution is a block of code
  314. 314. Blocks are delimited with braces { … } </li></ul>
  315. 315. Conditional Constructs <ul><li>Conditional blocks are controlled by the evaluation of an expression to see if it is true or false
  316. 316. But what is truth? </li></ul>
  317. 317. What is Truth? <ul><li>In Perl it's easier to answer the question &quot;what is false?&quot;
  318. 318. 0 (the number zero)‏
  319. 319. '' (the empty string)‏
  320. 320. undef (an undefined value)‏
  321. 321. () (an empty list)‏
  322. 322. Everything else is true </li></ul>
  323. 323. Comparison Operators <ul><li>Compare two values in some way
  324. 324. Are they equal </li><ul><li>$x == $y or $x eq $y
  325. 325. $x != $y or $x ne $y </li></ul><li>Is one greater than another </li><ul><li>$x > $y or $x gt $y
  326. 326. $x >= $y or $x ge $y </li></ul></ul>
  327. 327. Comparison Operators <ul><li>Is one less than another </li><ul><li>$x < $y or $x lt $y
  328. 328. $x <= $y or $x le $y </li></ul></ul>
  329. 329. Comparison Examples <ul><li>62 > 42 # true
  330. 330. '0' == (3 * 2) - 6 # true
  331. 331. 'apple' gt 'banana' # false
  332. 332. 'apple' == 'banana' # true(!)‏
  333. 333. 1 + 2 == '3 bears' # true
  334. 334. 1 + 3 == 'three' # false </li></ul>
  335. 335. Boolean Operators <ul><li>Combine conditional expressions
  336. 336. EXPR_1 and EXPR_2 </li><ul><li>true if both EXPR_1 and EXPR_2 are true </li></ul><li>EXPR_1 or EXPR_2 </li><ul><li>true if either EXPR_1 or _EXPR_2 are true </li></ul><li>Alternative syntax && for and and || for or
  337. 337. Different precedence though </li></ul>
  338. 338. Short-Circuit Operators <ul><li>EXPR_1 or EXPR_2
  339. 339. Only need to evaluate EXPR_2 if EXPR_1 evaluates as false
  340. 340. We can use this to make code easier to follow
  341. 341. open FILE, 'something.dat' or die &quot;Can't open file: $!&quot;;
  342. 342. @ARGV == 2 or print $usage_msg; </li></ul>
  343. 343. if <ul><li>if - our first conditional
  344. 344. if (EXPR) { BLOCK }
  345. 345. Only executes BLOCK if EXPR is true
  346. 346. if ($name eq 'Doctor') { regenerate(); } </li></ul>
  347. 347. if ... else ... <ul><li>if … else ... - an extended if
  348. 348. if (EXPR) { BLOCK1 } else { BLOCK2 }
  349. 349. If EXPR is true, execute BLOCK1, otherwise execute BLOCK2
  350. 350. if ($name eq 'Doctor') { regenerate(); } else { die &quot;Game over! &quot;; } </li></ul>
  351. 351. if ... elsif ... else ... <ul><li>if … elsif … else … - even more control
  352. 352. if (EXPR1) { BLOCK1 } elsif (EXPR2) { BLOCK2 } else { BLOCK3 } </li></ul>
  353. 353. if ... elsif ... else ... <ul><li>If EXPR1 is true, execute BLOCK1 else if EXPR2 is true, execute BLOCK2 otherwise execute BLOCK3 </li></ul>
  354. 354. if ... elsif ... else ... <ul><li>An example
  355. 355. if ($name eq 'Doctor') { regenerate(); } elsif ($tardis_location eq $here) { escape(); } else { die &quot;Game over! &quot;; } </li></ul>
  356. 356. while <ul><li>while - repeat the same code
  357. 357. while (EXPR) { BLOCK }
  358. 358. Repeat BLOCK while EXPR is true
  359. 359. while ($dalek_prisoners) { print &quot;Ex-ter-min-ate &quot;; $dalek_prisoners--; } </li></ul>
  360. 360. until <ul><li>until - the opposite of while
  361. 361. until (EXPR) { BLOCK }
  362. 362. Execute BLOCK until EXPR is true
  363. 363. until ($regenerations == 12) { print &quot;Regenerating &quot;; regenerate(); $regenerations++; } </li></ul>
  364. 364. for <ul><li>for - more complex loops
  365. 365. for (INIT; EXPR; INCR) { BLOCK }
  366. 366. Like C
  367. 367. Execute INIT If EXPR is false, exit loop, otherwise execute BLOCK, execute INCR and retest EXPR </li></ul>
  368. 368. for <ul><li>An example
  369. 369. for ($i = 1; $i <= 10; $i++) { print &quot;$i squared is &quot;, $i * $i, &quot; &quot;; }
  370. 370. Used surprisingly rarely </li></ul>
  371. 371. foreach <ul><li>foreach - simpler looping over lists
  372. 372. foreach VAR (LIST) { BLOCK }
  373. 373. For each element of LIST, set VAR to equal the element and execute BLOCK
  374. 374. foreach $i (1 .. 10) { print &quot;$i squared is &quot;, $i * $i, &quot; &quot;; } </li></ul>
  375. 375. foreach <ul><li>Another example
  376. 376. my %months = (Jan => 31, Feb => 28, Mar => 31, Apr => 30, May => 31, Jun => 30, … ); foreach (keys %months) { print &quot;$_ has $months{$_} days &quot;; } </li></ul>
  377. 377. Using while Loops <ul><li>Taking input from STDIN
  378. 378. while (<STDIN>) { print; }
  379. 379. This is the same as
  380. 380. while (defined($_ = <STDIN>)) { print $_; } </li></ul>
  381. 381. Breaking Out of Loops <ul><li>next – jump to next iteration of loop
  382. 382. last – jump out of loop
  383. 383. redo – jump to start of same iteration of loop </li></ul>
  384. 384. Subroutines
  385. 385. Subroutines <ul><li>Self-contained &quot;mini-programs&quot; within your program
  386. 386. Make it easy to repeat code
  387. 387. Subroutines have a name and a block of code
  388. 388. sub NAME { BLOCK } </li></ul>
  389. 389. Subroutine Example <ul><li>sub exterminate { print &quot;Ex-Ter-Min-Ate!! &quot;; $timelords--; } </li></ul>
  390. 390. Calling a Subroutine <ul><li>&exterminate;
  391. 391. exterminate();
  392. 392. exterminate;
  393. 393. last one only works if function has been predeclared </li></ul>
  394. 394. Subroutine Arguments <ul><li>Functions become far more useful if you can pass arguments to them
  395. 395. exterminate('The Doctor');
  396. 396. Arguments end up in the @_ array within the function </li></ul>
  397. 397. Subroutine Arguments <ul><li>sub exterminate { my ($name) = @_; print &quot;Ex-Ter-Min-Ate $name &quot;; $timelords--; } </li></ul>
  398. 398. Multiple Arguments <ul><li>As @_ is an array it can contain multiple arguments
  399. 399. sub exterminate { foreach (@_) { print &quot;Ex-Ter-Min-Ate $_ &quot;; $timelords--; } } </li></ul>
  400. 400. Calling Subroutines <ul><li>A subtle difference between &my_sub and my_sub()‏
  401. 401. &my_sub passes on the contents of @_ to the called subroutine
  402. 402. sub first { &second }; sub second { print @_ }; first('some', 'random', 'data');
  403. 403. You usually don't want to do that </li></ul>
  404. 404. By Value or Reference <ul><li>Passing by value passes the value of the variable into the subroutine. Changing the argument doesn't alter the external variable
  405. 405. Passing by reference passes the actual variable. Changing the argument alters the external value
  406. 406. Perl allows you to choose </li></ul>
  407. 407. Pass By Value <ul><li>Simulating pass by value
  408. 408. my ($arg1, $arg2) = @_;
  409. 409. Updating $arg1 and $arg2 doesn’t effect anything outside the subroutine </li></ul>
  410. 410. Pass By Reference <ul><li>Simulating pass by reference
  411. 411. $_[0] = 'whatever';
  412. 412. Updating the contents of @_ updates the external values </li></ul>
  413. 413. Returning Values <ul><li>Use return to return a value from a subroutine
  414. 414. sub exterminate { if (rand > .25) { print &quot;Ex-Ter-Min-Ate $_[0] &quot;; $timelords--; return 1; } else { return; } } </li></ul>
  415. 415. Returning a List <ul><li>Subroutines can return lists
  416. 416. sub exterminate { my @exterminated; foreach (@_) { if (rand > .25) { print &quot;Ex-Ter-Min-Ate $_ &quot;; $timelords--; push @exterminated, $_; } } return @exterminated; } </li></ul>
  417. 417. Regular Expressions
  418. 418. Regular Expressions <ul><li>Patterns that match strings
  419. 419. A bit like wild-cards
  420. 420. A “mini-language” within Perl </li><ul><li>Alien DNA </li></ul><li>The key to Perl's text processing power
  421. 421. Sometimes overused!
  422. 422. Documented in perldoc perlre </li></ul>
  423. 423. Match Operator <ul><li>m/PATTERN/ - the match operator
  424. 424. Works on $_ by default
  425. 425. In scalar context returns true if the match succeeds
  426. 426. In list context returns list of &quot;captured&quot; text
  427. 427. m is optional if you use / characters
  428. 428. With m you can use any delimiters </li></ul>
  429. 429. Match Examples <ul><li>while (<FILE>) { print if /foo/; print if /bar/i; print if m|http://|; } </li></ul>
  430. 430. Substitutions <ul><li>s/PATTERN/REPLACEMENT/ - the substitution operator
  431. 431. Works on $_ by default
  432. 432. In scalar context returns true if substitution succeeds
  433. 433. In list context returns number of replacements
  434. 434. Can choose any delimiter </li></ul>
  435. 435. Substitution Examples <ul><li>while (<FILE>) { s/teh/the/gi; s/freind/friend/gi; s/sholud/should/gi; print; } </li></ul>
  436. 436. Binding Operator <ul><li>If we want m// or s/// to work on something other than $_ then we need to use the binding operator
  437. 437. $name =~ s/Dave/David/; </li></ul>
  438. 438. Metacharacters <ul><li>Matching something other than literal text
  439. 439. ^ - matches start of string
  440. 440. $ - matches end of string
  441. 441. . - matches any character (except )‏
  442. 442. s - matches a whitespace character
  443. 443. S - matches a non-whitespace character </li></ul>
  444. 444. More Metacharacters <ul><li>d - matches any digit
  445. 445. D - matches any non-digit
  446. 446. w - matches any &quot;word&quot; character
  447. 447. W - matches any &quot;non-word&quot; character
  448. 448.  - matches a word boundary
  449. 449. B - matches anywhere except a word boundary </li></ul>
  450. 450. Metacharacter Examples <ul><li>while (<FILE>) { print if m|^http|; print if /perl/; print if /S/; print if /$d.dd/; } </li></ul>
  451. 451. Quantifiers <ul><li>Specify the number of occurrences
  452. 452. ? - match zero or one
  453. 453. * - match zero or more
  454. 454. + - match one or more
  455. 455. {n} - match exactly n
  456. 456. {n,} - match n or more
  457. 457. {n,m} - match between n and m </li></ul>
  458. 458. Quantifier Examples <ul><li>while (<FILE>) { print if /whiske?y/i; print if /so+n/; print if /d*.d+/; print if /Aw{3}/; } </li></ul>
  459. 459. Character Classes <ul><li>Define a class of characters to match
  460. 460. /[aeiou]/ # match any vowel
  461. 461. Use - to define a contiguous range
  462. 462. /[A-Z]/ # match upper case letters
  463. 463. Use ^ to match inverse set
  464. 464. /[^A-Za-z] # match non-letters </li></ul>
  465. 465. Alternation <ul><li>Use | to match one of a set of options
  466. 466. /rose|martha|donna/i;
  467. 467. Use parentheses for grouping
  468. 468. /^(rose|martha|donna)$/i; </li></ul>
  469. 469. Capturing Matches <ul><li>Parentheses are also used to capture parts of the matched string
  470. 470. The captured parts are in $1 , $2 , etc…
  471. 471. while (<FILE>) { if (/^(w+)s+(w+)/) { print &quot;The first word was $1 &quot;; print &quot;The second word was $2&quot;; } } </li></ul>
  472. 472. Returning Captures <ul><li>Captured values are also returned if the match operator is used in list context
  473. 473. my @nums = $text =~ /(d+)/g; print &quot;I found these integers: &quot;; print &quot;@nums &quot;; </li></ul>
  474. 474. More Information <ul><li>perldoc perlre
  475. 475. perldoc perlretut
  476. 476. Mastering Regular Expressions – Jeffrey Freidl </li></ul>
  477. 477. Smart Matching
  478. 478. Smart Matching <ul><li>Introduced in Perl 5.10
  479. 479. Powerful matching operator
  480. 480. DWIM
  481. 481. Examines operands
  482. 482. Decides which match to apply </li></ul>
  483. 483. Smart Match Operator <ul><li>~~
  484. 484. New operator
  485. 485. Looks a bit like the binding operator ( =~ )
  486. 486. Can be used in place of it
  487. 487. $some_text =~ /some regex/
  488. 488. Can be replaced with
  489. 489. $some_text ~~ /some regex/ </li></ul>
  490. 490. Smarter Matching <ul><li>If one of its operands is a regex
  491. 491. ~~ does a regex match
  492. 492. Cleverer than that though
  493. 493. %hash ~~ /regex/
  494. 494. Regex match on hash keys
  495. 495. @array ~~ /regex/
  496. 496. Regex match on array elements </li></ul>
  497. 497. More Smart Matches <ul><li>@array1 ~~ @array2
  498. 498. Checks that arrays are the same
  499. 499. $scalar ~~ @array
  500. 500. Checks scalar exists in array
  501. 501. $scalar ~~ %hash
  502. 502. Checks scalar is a hash key </li></ul>
  503. 503. Smart Scalar Matches <ul><li>What kind of match does this do?
  504. 504. $scalar1 ~~ $scalar2
  505. 505. It depends
  506. 506. If both look like numbers
  507. 507. ~~ acts like ==
  508. 508. Otherwise
  509. 509. ~~ acts like eq </li></ul>
  510. 510. Finding and Using Modules
  511. 511. Modules <ul><li>A module is a reusuable 'chunk' of code
  512. 512. Perl comes with over 100 modules (see “perldoc perlmodlib” for list)
  513. 513. Perl has a repository of freely-available modules - the Comprehensive Perl Archive Network (CPAN) </li><ul><li>http://www.cpan.org
  514. 514. http://search.cpan.org </li></ul></ul>
  515. 515. Finding Modules <ul><li>http://search.cpan.org
  516. 516. Search by: </li><ul><li>module name
  517. 517. distribution name
  518. 518. author name </li></ul><li>Note: CPAN also contains newer versions of standard modules </li></ul>
  519. 519. Installing Modules (The Hard Way) <ul><li>Download distribution file </li><ul><li>MyModule-X.XX.tar.gz </li></ul><li>Unzip </li><ul><li>$ gunzip MyModule-X.XX.tar.gz </li></ul><li>Untar </li><ul><li>$ tar xvf MyModule-X.XX.tar </li></ul><li>Change directory </li><ul><li>$ cd MyModule-X.XX </li></ul></ul>
  520. 520. Installing Modules (The Hard Way) <ul><li>Create Makefile </li><ul><li>$ perl Makefile.PL </li></ul><li>Build Module </li><ul><li>$ make </li></ul><li>Test Build </li><ul><li>$ make test </li></ul><li>Install Module </li><ul><li>$ make install </li></ul></ul>
  521. 521. Installing Modules (The Hard Way) <ul><li>Note: May need root permissions for make install
  522. 522. You can have your own personal module library
  523. 523. perl Makefile.PL PREFIX=~/perl </li><ul><li>need to adjust @INC </li></ul></ul>
  524. 524. Installing Modules (The Easy Way) <ul><li>CPANPLUS.pm is included with newer Perls
  525. 525. Automatically carries out installation process
  526. 526. Can also handle required modules </li></ul>
  527. 527. Installing Modules (The Easy Way) <ul><li>May not work (or may need some configuration) through a firewall
  528. 528. May still need to be root </li><ul><li>Can use 'sudo' </li></ul></ul>
  529. 529. Installing Modules (The Easy Way) <ul><li>cpanp [ ... some stuff ... ] CPAN Terminal> install Some::Module [ ... some more stuff ... ] CPAN Terminal> quit
  530. 530. Or
  531. 531. cpanp -i Some::Module </li></ul>
  532. 532. Using Modules <ul><li>Two types of module: </li><ul><li>Functions vs Objects </li></ul><li>Functional modules export new subroutines and variables into your program
  533. 533. Object modules usually don't
  534. 534. Difference not clear cut (e.g. CGI.pm) </li></ul>
  535. 535. Using Functional Modules <ul><li>Import defaults:
  536. 536. use My::Module;
  537. 537. Import optional components:
  538. 538. use My::Module qw(my_sub @my_arr); </li></ul>
  539. 539. Using Functional Modules <ul><li>Import defined sets of components:
  540. 540. use My:Module qw(:advanced);
  541. 541. Use imported components:
  542. 542. $data = my_sub(@my_arr); </li></ul>
  543. 543. Using Object Modules <ul><li>Use the module:
  544. 544. use My::Object;
  545. 545. Create an object:
  546. 546. $obj = My::Object->new; </li><ul><li>Note: new is just a convention </li></ul><li>Interact using object's methods
  547. 547. $obj->set_name($name); </li></ul>
  548. 548. Useful Standard Modules <ul><li>constant
  549. 549. Time::Local
  550. 550. Text::ParseWords
  551. 551. Getopt::Std
  552. 552. Cwd
  553. 553. File::Basename </li></ul><ul><li>File::Copy
  554. 554. POSIX
  555. 555. CGI
  556. 556. Carp
  557. 557. Benchmark
  558. 558. Data::Dumper </li></ul>
  559. 559. Useful Non-Standard Modules <ul><li>Template
  560. 560. DBI
  561. 561. DBIx::Class
  562. 562. DateTime
  563. 563. HTML::Parser
  564. 564. HTML::Tidy </li></ul><ul><li>LWP
  565. 565. WWW::Mechanize
  566. 566. Email::Simple
  567. 567. XML::LibXML
  568. 568. XML::Feed
  569. 569. Moose </li></ul>
  570. 570. That's All Folks <ul><li>Any Questions? </li></ul>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×