Writing Safe Code

Examples for the effect of my in functions

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

Example 1

#!/usr/local/bin/perl

my $n = 2000;
foo ();

sub foo {
   print "n: $n\n";
}
Output:
n: 2000
The foo subroutine recognized $n which was declared with my in the main program. This happened because foo is in the same file as the main program. if foo was in another file, it would not have recognize $n.

Example 2

#!/usr/local/bin/perl

foo ();
print "n: $n\n";

sub foo {
   my $n = 1999;
}
Output:
n:
The main program did not recognize the $n variable, which was declared with my inside the foo subroutine.

Example 3

#!/usr/local/bin/perl

foo ();

sub foo {
   my $n = 1999;
   bar ();
}

sub bar {
   print "n: $n\n";
}
Output:
n:
The $n variable which was declared with my inside the foo subroutine, was not recognized in the bar subroutine called from foo (bar).

Example 4

#!/usr/local/bin/perl

foo ();

sub foo {
   local $n = 1999;
   bar ();
}

sub bar {
   print "n: $n\n";
}
Output:
n: 1999
If the $n variable is declared with local inside the foo subroutine, it is recognized in bar.
Table of Contents.
Next.