Perl Programming/Declarations

Previous: Control flow Index Next: Operators

Declarations edit

You don't need to worry about declaring anything in Perl other than report formats and subroutines (sometimes not even subroutines). A scalar variable ($) will hold an undef value until it has been properly assigned a definite value (anything other than undef). When the scalar is used as a number, it will be treated as 0. When used as a string, it will be treated as an empty string "". If you use warnings you will normally be warned when there is an uninitialised value in your code, but not always.

Say for example you had:

if ($b) {}

This would not raise an error, as it is a boolean value. Boolean values are treated as true or false and do not require to be defined.

A declaration can be put anywhere a statement can and will not affect the overall running of the program. The declarations will be read when the program is being compiled. Typically, however, declarations are commonly defined at the beginning or the end of the program and other developers will appreciate this more than you just randomly declaring them.

Declaring a subroutine allows a subroutine name to be used as if it were a list operator. It is acceptable to declare a subroutine without defining it:

sub example;

my $element = example($i) or die "the process failed.";
Previous: Control flow Index Next: Operators