Perl Cheat Sheet Page 4

ADVERTISEMENT

2. Syntax
Perl is a free-format programming language. This means that in general it does not
matter how the Perl program is written with regard to indentation and lines.
An exception to this rule is when the Perl compiler encounters a ‘sharp’ symbol
( # ) in the input: it then discards this symbol and everything it follows up to the end
of the current input line. This can be used to put comments in Perl programs. Real
programmers put lots of useful comments in their programs.
There are places where whitespace does matter: within literal texts, patterns and
formats.
If the Perl compiler encounters the special token _ _END_ _ it discards this symbol
and stops reading input. Anything following this token is ignored by the Perl
compiler, but can be read by the program when it is run.
3. Variables
a simple scalar variable.
$var
29th element of array @var .
$var[28]
now $p is a reference to array @var .
$p = \@var
29th element of array referenced by $p . Also: $p->[28] .
$$p[28]
last element of array @var .
$var[-1]
$var[$i][$j]
$j -th element of $i -th element of array @var .
a value from ‘hash’ (associative array) %var .
$var{’Feb’}
$p = \%var
now $p is a reference to hash %var .
a value from hash referenced by $p . Also: $p->{’Feb’} .
$$p{’Feb’}
last index of array @var .
$#var
the entire array;
@var
in a scalar context, the number of elements in the array.
a slice of array @var .
@var[3,4,5]
@var{’a’,’b’} a slice of %var ; same as ($var{’a’},$var{’b’}) .
the entire hash;
%var
in a scalar context, true if the hash has elements.
$var{’a’,1,...} emulates a multi-dimensional array.
(’a’..’z’)[4,7,9] a slice of an array literal.
PKG
VAR
a variable from a package, e.g. $pkg::var , @pkg::ary .
::
reference to a thingie, e.g. \$var , \%hash .
\
THINGIE
refers to all thingies represented by
.
*
NAME
NAME
‘ *n1 = *n2 ’ makes n1 an alias for n2 .
‘ *n1 = \$n2 ’ makes $n1 an alias for $n2 .
You can always use a {
} returning the right type of reference instead of
BLOCK
the variable identifier, e.g. ${ . . . } , &{ . . . } . $$p is just a shorthand for ${$p} .
4

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education