Scripts

  • A common extension for Perl scripts is .pl, or .cgi for CGI scripts

Shebang

  • The first line must be one of the following, to indicate that the file is a Perl script:
  • #!/usr/bin/perl
  • #!/usr/local/bin/perl
  • #!/usr/bin/env perl
  • In the above examples, the -w option can be added to display warnings, which are helpful for debugging the script
  • There's some controversy over which of the above approaches is best
  • To find out which location perl is run from on a given computer, type which perl

Perl CGI scripts

  • When printing content for display in a web browser, the first print command must contain an http header:
  • print "Content-type: text/plain \n\n";  # To output plain text
  • print "Content-type: text/html \n\n";  # To output html

Pragmas

  • The use keyword in Perl directs the interpreter to either load a module or turn a pragma on.
use strict;
  • Enforces strict error-checking
  • The only time it shouldn't be used is when variables are dynamically exported
  • Commonly placed as the second line in the script
  • The "use strict" pragma requires that all variables be defined before they are used
  • Have to fully qualify a variable (such as $packagename::varname), import the variable (such as happens with 'use' or 'import'), or specifically tell the processor that you want this variable to be used as global (such as use vars ('%formdata'))
use vars qw($my_scalar @my_array %my_hash);
  • Perl pragma that predeclares all the variables whose names are in the list, allowing them to be used under use strict, and disabling any typo warnings
  • Applies to the entire file in which it appears; cannot be rescinded with no vars
use subs qw(foo1 foo2);
  • Perl pragma that predeclares all the subroutines whose names appear in the list, allowing them to be used without parentheses even before they're declared
  • Applies to the entire file in which it appears; cannot be rescinded with no subs
use constant
  • Perl pragma that defines constants
  • Constants are stored as lists by default
  • Use the scalar operator to cause a constant to be treated as a scalar value
  • Put the constant in parentheses to access an element of the list
use constant CHILDREN => 3;           # 3 children per process
use constant PI => scalar 3.14; # 2 digits of precision
use constant MESSAGE => "Hello"; # a message
$homedir = (USERINFO)[7];      # Access an element of a list constant

Misc

use warnings;
use integer;
use bytes;
use utf8;
use re;
  • Assigning to the special variable $[