Chapter 8. Variables

$var

A simple scalar variable.

$p = $var

Now $p is a reference to scalar $var.

$$p

The scalar referenced by $p.

@var

An array. In scalar context, the number of elements in the array.

$var[6]

Seventh element of array @var.

$var[-1]

The last element of array @var.

$p = @var

Now $p is a reference to array @var.

$$p[6] or $p->[6]

Seventh element of array referenced by $p.

${$p[6]}

The scalar referenced by $p[6].

$p = $var[6]

Now $p is a reference to the seventh element of array @var.

$p = [1,3,'ape']

Now $p is a reference to an anonymous array with three elements.

$var[$i][$j]

$j-th element of $i-th element of array @var.

$#var

Last index of array @var.

@var[3,4,5]

A slice of array @var.

%var

A hash. In scalar context, true if the hash has elements.

$var{'red'} or $var{red}

A value from hash %var. The hash key may be specified without quotes if it is simple identifier.

$p = \%var

Now $p is a reference to hash %var.

$$p{'red'} or $p->{'red'}

A value from the hash referenced by $p.

${$p{'red'}}

The scalar referenced by $p{'red'}.

$p = {red => 1, blue => 2, yellow => 3}

Now $p is a reference to an anonymous hash with three elements.

@var{'a','b'}

A slice of %var; same as ($var{'a'},$var{'b'}).

$var{'a',1, ... }

Multidimensional hash (obsolete).

$c = &mysub

Now $c is a reference to subroutine mysub.

&$c( args ) or $c->( args )

A call to the subroutine via the reference.

$c = sub { ... }

Now $c is a reference to an anonymous subroutine.

pkg::var

A variable from a package, e.g., $pkg::var, @pkg::ary. The default package is main.

*name

Symbol table entry (typeglob). Refers to everything represented by name.

*n1{SCALAR} is the same as $n1; *n1{ARRAY} is the same as @n1. Other possibilities are HASH, CODE, GLOB, and IO.

Package variables can be aliased by assigning a reference to the typeglob:

  • *n1 = $n2 makes $n1 an alias for $n2.

  • *n1 = *n2 makes all n1 aliases for n2.

Instead of the variable identifier, a block that returns the right type of reference can be used. For example, ${ $x > 0 ? $y[4] : $z }.

perldata, perlref.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset