Table of Contents

Variable Scope

To bring things back to Perl, a short diversion is necessary to illustrate the point with actual Perl code instead of canine metaphors:

$pet ='dog';
$age =3;

print "$name the $pet is aged $age\n";

	my $age =4;	  # run this again, but comment this line out
	my $name='Spot';  # and this one
	$pet    ='cat';

	print "$name the $pet is aged $age\n";

print "$name the $pet is aged $age\n";

This is pretty straightforward until we get to the { . This marks the start of a block. One feature of a block is that it can have its own namespace. Variables declared, in other words initialised, within that block are just normal variables, unless they are declared with my .

When variables are declared with my they are visible inside the block only. Also, any variable which has the same name outside the block is ignored. Points to note from the example above: