Piled Perl Remarks

Most parts of this document are shamelessly stolen from the Perl manual pages.

Loops

while
while (<[gt    ]&{
    ...;
for
for ($i = 1; $i < 10; $i++) {
    ...
}
foreach [VAR] LIST EXPR
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop.

The keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity. If VAR is omitted, $_ is set to each value. If LIST is an actual array (as opposed to an expression returning a list value), you can modify each element of the array by modifying VAR inside the loop. That's because the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

for (@ary) { s/foo/bar/ }

foreach my $elem (@elements) {
    $elem *= 2;
}

Extracting Substrings

substr EXPR OFFSET [LEN]
Extracts a substring out of EXPR and returns it. First character is at offset 0, or whatever you've set $[ to. If OFFSET is negative, starts that far from the end of the string. If LEN is omitted, returns everything to the end of the string. If LEN is negative, leaves that many characters off the end of the string.

You can use the substr function as an lvalue, in which case EXPR must be an lvalue. If you assign something shorter than LEN, the string will shrink, and if you assign something longer than LEN, the string will grow to accommodate it. To keep the string the same length you may need to pad or chop your value using sprintf.

Case Conversion

lc EXPR
Returns an lowercased version of EXPR. This is the internal function implementing the \L escape in double- quoted strings. Should respect any POSIX setlocale() settings.
lcfirst EXPR
Returns the value of EXPR with the first character lowercased. This is the internal function implementing the \l escape in double-quoted strings. Should respect any POSIX setlocale() settings.
uc EXPR
Returns an uppercased version of EXPR . This is the internal function implementing the \U escape in double-quoted strings. Should respect any POSIX setlocale() settings.
ucfirst EXPR
Returns the value of EXPR with the first character uppercased. This is the internal function implementing the \u escape in double-quoted strings. Should respect any POSIX setlocale() settings.

Executing System Commands

A string enclosed by backticks ( grave accents) first undergoes variable substitution just like a double quoted string. It is then interpreted as a command, and the output of that command is the value of the pseudo-literal, like in a shell. In a scalar context, a single string consisting of all the output is returned. In a list context, a list of values is returned, one for each line of output. (You can set $/ to use a different line terminator.) The command is executed each time the pseudo-literal is evaluated. The status value of the command is returned in $?.
% perl -e 'print `date`'
Wed Sep 24 22:36:58 MET DST 1997

Environment Variables

Each element of the hash array %ENV corresponds to an environment variable, e.g. the list of directories to search for executable programs is stored in $ENV{PATH} . Setting a value in %ENV changes the environment for child processes.

Modules

Creating Modules

The first step is to create the module infrastructure. The following example is valid for vanilla Perl modules:
racke#~/castwine h2xs -f -X -n CGI::Db
Writing CGI/Db/Db.pm
Writing CGI/Db/Makefile.PL
Writing CGI/Db/test.pl
Writing CGI/Db/Changes
Writing CGI/Db/MANIFEST

References

Creating References

References can be created by using the backslash operator on a variable, subroutine or value, just like the address-of-operator (&) in C.
$scalarref = \$foo;
$arrayref  = \@ARGV;
$hashref   = \%ENV;
$coderef   = \&handler;
$globref   = \*STDOUT;

Using References

Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a simple scalar variable containing a reference of the correct type:
$bar = $$scalarref;
push(@$arrayref, $filename);
$$arrayref[0] = "January";
for (my $i = 0; $i <= $#$arrayref; $i++) {print "Month: $$arrayref[$i]\n";}
$$hashref{"KEY"} = "VALUE";
&$coderef(1,2,3);
print $globref "output\n";
It's important to understand that we are specifically not dereferencing $arrayref[0] or $hashref{"KEY"} there. The dereference of the scalar variable happens before it does any key lookups.

Prototypes

Prototypes were introduced by the 5.002 release of Perl. A script or module using prototypes should include the statement
BEGIN {require 5.002;}		# we're using prototypes
Note that a bare require statement isn't sufficient.

Autoloading

If you call a subroutine that is undefined, you would ordinarily get an immediate fatal error complaining that the subroutine doesn't exist. (Likewise for subroutines being used as methods, when the method doesn't exist in any base class of the class package.) If, however, there is an AUTOLOAD subroutine defined in the package or packages that were searched for the original subroutine, then that AUTOLOAD subroutine is called with the arguments that would have been passed to the original subroutine. The fully qualified name of the original subroutine magically appears in the $AUTOLOAD variable in the same package as the AUTOLOAD routine. The name is not passed as an ordinary argument because, er, well, just because, that's why...

Most AUTOLOAD routines will load in a definition for the subroutine in question using eval, and then execute that subroutine using a special form of "goto" that erases the stack frame of the AUTOLOAD routine without a trace. (See the standard AutoLoader module, for example.) But an AUTOLOAD routine can also just emulate the routine and never define it. For example, let's pretend that a function that wasn't defined should just call system() with those arguments. All you'd do is this:

sub AUTOLOAD {
    my $program = $AUTOLOAD;
    $program =~ s/.*:://;
    system($program, @_);
}
date();
who('am', 'i');
ls('-l');

Database Interface

database inteface
prepare $statement [\%attr]
Prepare a single statement for execution by the database engine and return a reference to a statement handle object which can be used to get attributes of the statement and invoke the execute method later on.
execute [@bind_values]
Perform whatever processing is necessary to execute the prepared statement. An undef is returned if an error occurs, a successful execute always return true regardless of the number of rows affected.

Writing CGI Scripts

This section describes how to write CGI scripts with Perl and the CGI modules.

Creating a Submit Button

Internationalization

Embedded Documentation

Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this
=head1 Here There Be Pods!
Then that text and all remaining text up through and including a line beginning with =cut will be ignored. The format of the intervening text is described in the perlpod manpage.

This allows you to intermix your source code and your documentation text freely, as in

=item snazzle($)

The snazzle() function will behave in the most spectacular
form that you can possibly imagine, not even excepting
cybernetic pyrotechnics.

=cut back to the compiler, nuff of this pod stuff!

sub snazzle($) {
    my $thingie = shift;
    .........
}
Note that pod translators should only look at paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators.
$a=3;
=secret stuff
warn "Neither POD nor CODE!?"
=cut back
print "got $a\n";
You probably shouldn't rely upon the warn() being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier.

Module Index

Index of Functions

Index of Variables

Concept Index


Written by Stefan Hornburg <racke@gundel.han.de>
Translated from perlrem.sgml by Info Prism's sgml2html v0.0.6
Last modified 13 January 1999