Perl Tutorial: Syllabus
- Instructor:
- Mordechai T. Abzug
- Dates & times:
- 2001-10-23 @ 7pm
- Prereqs:
- C. It would also help if you're already
familiar with any other shell programming language.
- Suggested book:
-
Programming Perl, by Larry Wall, Tom Christiansen, and Randal Schwartz,
published by ora.com.
Notes
The following notes will probably make no sense unless you have some prior
perl experience.
Introduction
- Background on Perl:
- Larry Wall
- sysadminning/history
- related to: C, sh/csh, sed/awk, BASIC
- "perl -v", perl5 vs. perl4, perl5.005
- formal programming language vs. quick hack language
- perldoc perl
- Interpreted
- Interpreted vs. compiled
- Interpretted
- Easy to debug, easy to modify, source code
is always available, loads slowly
- Compiled
- Hard to debug, hard to modify, source code is not
always available, loads faster
- perl: originally interpreted
- perl compiler
- modules, core and CPAN
- you can contribute!
- Hello, World!
- "foo" file containing
print "Hello, World\n";
- "perl foo"
- Make it an executable. In unix on gl: "#!/usr/bin/perl -w"
as first line, then chmod 700 foo.
- Unix generally: "which perl".
- Unix generally tricks for multiple perls
- bash: "perl<tab>"
- tcsh: "perl<^D>
- otherwise: stuck with "ls -l /bin/perl* /sbin/perl*
/usr/bin/perl* /usr/local/bin/perl*"
- DOS: batch file "foo.bat" wrapper
- Windows 9x
- Mac?
- use strict, -w
- Print
- Perl has printf, too. print is different.
- Does not automatically add a \n at the end of the line.
- Multiple args separated by commas are concatted (not like printf)
- Do *not* discuss file handles yet! :)
- Basic data types
- Scalar (ie. $foo): integers, floats, strings, references. Chars
are degenerate strings (like in shell programming and in BASIC)
- array: (ie. @foo): any list of scalars. C-style numbering.
Whole array: @foo. Single element: $foo[2]. Slice: @foo[2..4].
Anonymous: ('aa', 'bb', 'cc')
- hash: (ie. %foo): any associative array of scalars. Whole hash:
%foo. Single element: $foo{'field'}. [sort of like structs/ records].
Basic Data Types
- Scalars
- "$foo" means scalar
- integers, floats, strings, references; characters are degenerate
strings
- auto conversion (but -w warns): "186000 mi/s" + 4*1.5 results in
186006
- Booleans are integers: "", 0 are false. "0" is zero.
- interpolation: "" vs. '' (talk now about qq() vs. q()?)
- Partially replaces the need for printf and sprintf
- perldoc perldata
- Arrays (or Lists)
- @foo
- Anonymous arrays: ( 'a', 'b', 'c' ). (Show qw() now?)
- print takes a list; print "@foo"; differs from print @foo; (which
is like print 'a', 'b', 'c')
- Only array of scalars. Array references in perl allow C-style
multi-D arrays.
- $foo[0], $foo[5]
- Self extending (but show what happens when you switch on -w, use
strict, and use diagnostics)
- Scalar context (=length)
- $#foo (=last item = length - 1)
- @foo[2,4], @foo[2..4], @foo[1,3..5]
- ('x', @foo, 'y')
- join (";\t ", @foo)
- push, pop, shift, unshift (array as double-ended queue)
- splice (@foo, $offset, $length, (@list))
- $[=1 for Pascal behavior; strongly discouraged ( perldoc perlvar)
- Hashes. . . Skip this until after statements
- %foo, $foo{'bar'}
- each
- undef
- defined $foo{'bar'}, exists $foo{'bar'), $foo{'bar'}
- Declarations/ Scope
- no need for declarations -- intrinsic in variable name, BUT. . .
- my
- local -- don't use. ADVANCED.
- -w, use strict, use diagnostics
Control Statements and operators
- Control statments
- C-style if (){}, while (){}, for (;;){}, do {} while;
- no dangling statements -- must be in blocks
- so, instead of else if, perl has an elsif
- until, unless -- syntactic sugar
- postfix if, while, unless, until
- foreach
- next, last (=C's continue, break. Perl also has a continue.)
- perl's continue, redo. ADVANCED.
- Numerical operators
- C-style ==, <, >, <=, >=
- C-style =, +, -, *, /, %, +=, -=, *=, /=, %=
- Fortran-style **
- String ops: lt, gt, ne, eq, le, ge
- ternary operators: C-style (?:), and weird: <=>, cmp
Go hogwild
- Simple file ops
- umask 022
- open
- close
- <FILEHANDLE>
- chomp
- More on Hashes
- each, keys, values
- defined $f{a}, exists $f{a}, $f{a}: the three booleans
- undef
- Simple regex
- =~ //;
- \-special character rule
- .
- *
- \d, \D, \w, \W, \s, \S
- perldoc perlre
- m{}
- () and $1, etc.
- s{}{}, s{}{}g
- Useful/ cool stuff
- @ARGV (and $0)
- die, warn
- exit
- $_, @_: the magical defaults
- <>
- chomp = chomp $_
- shift = shift @_ or shift @ARGV
- require and use
- require "getopts.pl" or use Getopts::Std
- -l, -e, -n, -p, -i (don't forget -w!)
- Funky Functions
- sort
- chomp (chop)
- splice, reverse
- join
- grep, map
- fork, exec
- eval
- time, localtime, gmtime, POSIX's strftime
- glob
- context-sensitivity and wantarray
- perldoc perlfunc
- Your own functions (subroutines)
- sub foo {}
- &foo
- @_
- shift
- my, not local! (lexical vs. dynamic scoping). ADVANCED
- return
- perldoc perlsub
References, Multi-D and OOP
- References
- '\'
- \$scal, \&subrout, \@arr, \%hash
- ${$scal_ref}, &{$sub_ref}, @{$arr_ref}, %{$hash_ref}
- anonymous hash reference: {}
- anonymous array reference: []
- anonymous code reference: sub { BLOCK; } or even { BLOCK; }
- perldoc perlref
- Multi-D
- $foo[3][4] makes $foo[3] a reference to an anon array.
- Mix and match: $foo[3]{'bar'}[9][2]
- Modules
- ::
- ->
- File::stat
- Getopt::Std
- File::Basename
- Socket
- FileHandle
- POSIX
- FindBin
- English
- Config::IniFiles (from CPAN)
- SNMP_util (download)
- OOP. ADVANCED.
- Scoping via packages
- Normally implemented via "bless"ed hash references
Appendix A: creating a "Hello world" perl program on gl
Type the following, exactly as it apppears:
rm -f foo
touch foo
chmod 755 foo
cat >> foo <<EOF
#!/usr/bin/perl -w
print "Hello, World!\n";
EOF
./foo
Appendix B: a useful extension for your .emacs
If you add the below to your .emacs, you can type C-c C-f and run the
current buffer.
(add-hook 'perl-mode-hook '(lambda () (local-set-key [?\C-c ?\C-f] 'perl-run)))
(defvar perl-run-window-size '7 "*size of output screen for perl")
(defun perl-run () (interactive) (save-buffer)
(let* ((old-buffer (buffer-name))
(output-buffer "*Shell Command Output*"))
(shell-command (concat "./" old-buffer))
(set-buffer (get-buffer-create output-buffer))
(pop-to-buffer output-buffer)
(shrink-window (- (window-height) perl-run-window-size))
(pop-to-buffer old-buffer)
))