Presentation is loading. Please wait.

Presentation is loading. Please wait.

Llama to Ram How to think like a perl weenie Rob Napier 3/18/99.

Similar presentations


Presentation on theme: "Llama to Ram How to think like a perl weenie Rob Napier 3/18/99."— Presentation transcript:

1 Llama to Ram How to think like a perl weenie Rob Napier 3/18/99

2 Llama to Ram -- Rob Napier2 Introduction n In this talk we will move from the basics of perl syntax and grammar (Llama) to the philosophy behind perl and the tools of the trade (Ram). n This talk will not cover many advanced perl topics, and in particular won't cover performance issues or advanced data structures

3 3/18/99Llama to Ram -- Rob Napier3 Topics of Discussion n Background and philosophy n Perl basics n Tools of the trade n Pitfalls n Perl rules n Gotchas

4 3/18/99Llama to Ram -- Rob Napier4 Background and Philosophy n Quotes n Influences n O’Reilly Bestiary

5 3/18/99Llama to Ram -- Rob Napier5 Quotes n Practical Extraction and Report Language n Perl is a language for getting things done. n There’s more than one way to do it

6 3/18/99Llama to Ram -- Rob Napier6 Major Influences n C n sh n regex n unix n LISP and COBOL

7 3/18/99Llama to Ram -- Rob Napier7 O’Reilly Bestiary n Learning - Llama n Programming - Camel n Cookbook - Ram n Advanced - Leopard/Panther n Also Perl/Tk, Nutshell, Win32, and others

8 3/18/99Llama to Ram -- Rob Napier8 Perl Basics n Auto-conversion (coercion) n The search for Truth n Safety nets n Data types

9 3/18/99Llama to Ram -- Rob Napier9 Auto-conversion (coercion) n Strings Numbers n References => Strings n undef => Strings n Scalars => Lists n Lists => Scalar u The dreaded 1’s

10 3/18/99Llama to Ram -- Rob Napier10 The Search for Truth n False: “”, “0” u False = 0, undef, () u True = 1, ref, “0 but true”, and most anything else

11 3/18/99Llama to Ram -- Rob Napier11 Safety Nets n -w n use strict

12 3/18/99Llama to Ram -- Rob Napier12 Data types n Scalars n Lists n Hashes n Filehandles n References

13 3/18/99Llama to Ram -- Rob Napier13 Scalars n Numbers n Strings n References n undef n Typeglob n Filehandle $foo = “bar”;

14 3/18/99Llama to Ram -- Rob Napier14 Lists n Heterogeneous n Both list-like and array-like, but usually list-like @foo = qw(bar baz bang); $bing = @foo[4]; @bang = @foo[4, 6];

15 3/18/99Llama to Ram -- Rob Napier15 Hashes n Associate arrays n keys, values, each, delete, exists %foo = (apple => “red”, orange => “orange”, foo => 2); $foo{apple} = “orange”; @foo{apple, orange};

16 3/18/99Llama to Ram -- Rob Napier16 Filehandles n open (FOO, “foo”); n while ( ) { n while (<>) { n Includes predefined STDOUT, STDIN, STDERR

17 3/18/99Llama to Ram -- Rob Napier17 Typeglobs n Entries in the symbols table n Not used very often except for references to filehandles

18 3/18/99Llama to Ram -- Rob Napier18 References n Hard n Symbolic

19 3/18/99Llama to Ram -- Rob Napier19 Hard References n Similar to C-style pointers. $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*foo; $scalarref = \1; $arrayref = [1, 2, [‘a’, ‘b’, ‘c’]]; $hashref = {‘Adam’ => ‘Eve’, ‘Clyde’ => Bonnie’ }; $coderef = sub {print “Boink!\n” };

20 3/18/99Llama to Ram -- Rob Napier20 Symbolic References n Indirect references to variable n These can be very dangerous (and aren’t allowed under ‘use strict’) n $$scalarref; n @$arrayref; n %$hashref

21 3/18/99Llama to Ram -- Rob Napier21 Tools of the trade n Lists n Hashes n Regex n Subs n Modules

22 3/18/99Llama to Ram -- Rob Napier22 Lists n Usually used as lists, instead of arrays n qw() n Sets n Slurping

23 3/18/99Llama to Ram -- Rob Napier23 Lists, seldom arrays n Usually use foreach, rather than subscripting into arrays. Instead of: for ($i =0; $i <= $#list; $i++) { do_something($list[$i]); } Do this: foreach $elem (@list) { do_something($_); }

24 3/18/99Llama to Ram -- Rob Napier24 qw() n Very good way to set lists of quoted words: @foo = qw(this is a test);

25 3/18/99Llama to Ram -- Rob Napier25 Sets @isect = @diff = @union = (); foreach $e (@a, @b) { $count{$e}++ } foreach $e (keys %count) { push(@union, $e); push @{ $count{$e} == 2 ? \@isect : \@diff }, $e; }

26 3/18/99Llama to Ram -- Rob Napier26 Slurping n Often it’s handy to just slurp a whole file and work on it in memory: open(FOO, “foo”); @foo = ;

27 3/18/99Llama to Ram -- Rob Napier27 Hashes n Swiss-army knife of perl u Associative arrays u Records u “In list” applications

28 3/18/99Llama to Ram -- Rob Napier28 Associate Arrays %foo = (apple => “red”, orange => “orange”); print $foo{apple};

29 3/18/99Llama to Ram -- Rob Napier29 Records The hard way @entry = getpwuid($<); %user = (name => $entry[0], passwd => $entry[1], uid => $entry[2], gid => $entry[3], quota => $entry[4], comment => $entry[5], […], expire => $entry[9]); print “name is $user{name}\n”;

30 3/18/99Llama to Ram -- Rob Napier30 Records cont The easy way (i.e. the perl way) @fields = qw(name passwd uid gid quota comment gcos dir shell expire); @user{@fields} = getpwuid $<; print “name is $user{name}\n”;

31 3/18/99Llama to Ram -- Rob Napier31 “In list” applications n Maintaining list order sub unique { my (@list) = (@_); my %seen = (); # Hash to keep track of what we've seen my $item; # Current item my @uniq; # Unique list foreach $item (@list) { push (@uniq, $item) unless $seen{$item}++; } return @uniq; }

32 3/18/99Llama to Ram -- Rob Napier32 “In list” applications cont n Trashing list order sub unique { my (@list) = (@_) my %uniq; @uniq{@list} = (); return keys @uniq; }

33 3/18/99Llama to Ram -- Rob Napier33 Regex n Very useful for getting a lot of things done fast. Rob Napier: 9408 Erinsbrook Drive, Raleigh, NC 27613 (919)848-9523 /(.*):\s*([^,]*),\s*([^,]*),\s*(\w+)\s+(\d+)\s+(?=\()(.*)/ $name = $1; $address = $2; $city = $3; $state = $4; $zip = $5; $phone = $6;

34 3/18/99Llama to Ram -- Rob Napier34 Subs n Passing non-scalars n Returning non-scalars n Named parameters

35 3/18/99Llama to Ram -- Rob Napier35 Passing non-scalars n Try to move non-scalar to the end n If you can’t, pass a reference sub foo { my @a = @{shift()}; my @b = @{shift()}; print “@a\n”; print “@b\n”; } foo(\@bar, \@baz);

36 3/18/99Llama to Ram -- Rob Napier36 Returning non-scalars n If you can return it as a flat list (or hash), then just return it. n If you have multiple, distinct return values, return a list of references sub foo { my @a = qw(this is a test); my @b = qw(this is a test); return (\@a, \@b); }

37 3/18/99Llama to Ram -- Rob Napier37 Named parameters sub thefunc { my %args = ( INCREMENT => '10s', FINISH => 0, START => 0, @_, # argument pair list goes here ); if ($args{INCREMENT} =~ /m$/ ) {..... } } thefunc(INCREMENT => "20s", START => "+5m", FINISH => "+30m");

38 3/18/99Llama to Ram -- Rob Napier38 Modules n File::Path n File::Find n File::Copy n Exporter n getop n sendmail n CGI n Cwd

39 3/18/99Llama to Ram -- Rob Napier39 perl4 pitfalls n use strict! (and debatably also use -w) n local => my n chop => chomp n require => use n Avoid globals n Avoid typeglobs n Investigate complex data structures

40 3/18/99Llama to Ram -- Rob Napier40 sh pitfalls n use strict! n << instead of multiple prints n 0=false, 1=true except on system calls n Don’t over-fork. Most of what you want is in perl: rm/rm -rf, find, ls, echo, grep, awk, sed, pwd, mkdir, mkdir -p, chown, chgrp, cp, ln n Avoid globals

41 3/18/99Llama to Ram -- Rob Napier41 sh pitfalls (cont) n Don’t store lists as strings n Avoid temp files n Avoid excessive chdir()

42 3/18/99Llama to Ram -- Rob Napier42 C pitfalls n Avoid subscripting lists that you’re iterating over n printf -> print n Don’t fear labels, especially for using ‘last’ and ‘next’ n Don’t try to split a string character by character. Use regex. n Don’t overlook POSIX

43 3/18/99Llama to Ram -- Rob Napier43 General perl pitfalls n Generally you don’t need to add.pl onto script names. n Often readdir() is a better tool than glob() n tr/a-z/A-Z/ -> uc()

44 3/18/99Llama to Ram -- Rob Napier44 Perl rules n Always return() n Always check your system return codes and close() returns n use strict n $# => scalar (or scalar context) u Some people may debate this one, but I find it helps a lot. n Before writing anything complex, always check CPAN (www.cpan.com)

45 3/18/99Llama to Ram -- Rob Napier45 Gotchas n BEGIN { use strict; } n There is no real function prototype mechanism (perl prototypes aren’t what you think) n << EOF u Watch out for spaces before the EOF n != vs ne, == vs eq, + vs. u number vs. string

46 3/18/99Llama to Ram -- Rob Napier46 Gotchas cont n &&, ||, and, or u && and || bind tightly. “and” and “or” bind loosely u Generally, you use && and || in boolean logic, while “and” and “or” are used for “or die” type error checking. n print “@foo” vs print @foo u “@foo” adds spaces. This includes inside a HERE- docs

47 3/18/99Llama to Ram -- Rob Napier47 Gotchas cont n `foo` or warn u This only warns if `foo` returns no output (even if that output is an error) n split (‘ ‘,...) u Splits on whitespace /[ \n\t]+/, not just ‘ ‘.

48 3/18/99Llama to Ram -- Rob Napier48 Wrapup n Thinking like a perl weenie means working with the language instead of against it. Even though “there’s more than one way to do it,” many of those ways fail to make good use of the power that perl offers. n The best way to learn to think in perl is to keep trying to make working scripts more perl-like. The best solution is usually the shortest solution that is still readable.


Download ppt "Llama to Ram How to think like a perl weenie Rob Napier 3/18/99."

Similar presentations


Ads by Google