Your SlideShare is downloading. ×
0
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Introduction to Perl - Day 1
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to Perl - Day 1

76,576

Published on

Day 1 of the "Introducing Perl" training course that I ran at YAPC::Europe in Lisbon in August 2009.

Day 1 of the "Introducing Perl" training course that I ran at YAPC::Europe in Lisbon in August 2009.

Published in: Technology, Education
5 Comments
37 Likes
Statistics
Notes
No Downloads
Views
Total Views
76,576
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
2,962
Comments
5
Likes
37
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

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

×