- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

4.1 Declarations

The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines). A variable holds the undefined value (undef) until it has been assigned a defined value, which is anything other than undef. When used as a number, undef is treated as 0; when used as a string, it is treated as the empty string, ""; and when used as a reference that isn't being assigned to, it is treated as an error. If you enable warnings, you'll be notified of an uninitialized value whenever you treat undef as a string or a number. Well, usually. Boolean contexts, such as:

my $a;
if ($a) {}

are exempt from warnings (because they care about truth rather than definedness). Operators such as ++, --, +=, -=, and .=, that operate on undefined left values such as:

my $a;

are also always exempt from such warnings.

A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements--declarations all take effect at compile time. Typically all the declarations are put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with my(), you'll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables.

Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying sub name, thus:

sub myname;
$me = myname $0             or die "can't get myname";

Note that myname() functions as a list operator, not as a unary operator; so be careful to use or instead of || in this case. However, if you were to declare the subroutine as sub myname ($), then myname would function as a unary operator, so either or or || would work.

Subroutines declarations can also be loaded up with the require statement or both loaded and imported into your namespace with a use statement. See "Perl modules (packages and symbol tables)" (perlmod) in the Perl Library Reference Manual (Volume 2) for details on this.

A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects.

ISBN 9781906966027Perl Language Reference ManualSee the print edition