Writing Safe Code

Examples for the effect of my in loops

In the following programs we use the $n variable to demonstrate the effect of the my declaration with regard to a loop.

Example 1

#!/usr/local/bin/perl

my @a = ("Jan", "Feb", "Mar", "Apr");
my $n = 2000;

foreach $month (@a) {
   print "$month  $n\n";
}
Output:
Jan  2000
Feb  2000
Mar  2000
Apr  2000
The $n variable which was declared with my before the loop, was recognized inside the loop.

Example 2

#!/usr/local/bin/perl

my @a = ("Jan", "Feb", "Mar", "Apr");

foreach $month (@a) {
   #do something with $month here (not shown)
   my $n = 1999;
}

print "n: $n\n";
Output:
n:
$n, which was declared with my inside the loop, was not recognized outside the loop.

Example 3

#!/usr/local/bin/perl

my @a = ("Jan", "Feb", "Mar", "Apr");
my $n = 2000;

foreach $month (@a) {
   #do something with $month here (not shown)
   my $n = 1999;
}

print "n: $n\n";
Output:
n: 2000
The program printed $n as it was defined before the loop

Example 4

#!/usr/local/bin/perl

my @a = ("Jan", "Feb", "Mar", "Apr");
my $n = 2000;

foreach $month (@a) {
   #do something with $month here (not shown)
   $n = 1999;       #we removed the my declaration here
}

print "n: $n\n";
Output:
n: 1999
The program printed $n as it was defined inside the loop
Table of Contents.
Next.