Packages


Beginning | Previous | Next

Default Scope

When a variable or file handle comes into existence or a user function is defined, the default scope of these entities is bound to a package called "main". For example, these variables in this short program are all in the "main" package:

   /usr/local/bin/perl -w

   opendir (DIR, '.') || die "Can't open current dir: $!\n";
   @Files = readdir (DIR);
   closedir (DIR);
   foreach (@Files)
   {
      $Size = (stat ($_))[7];
      print "$_ has size $Size blocks\n";
   }

Why Packages?

Packages can help avoid name collisions in Perl programs. A perfect place to use them is in user libraries, such as: package UnixTools; $Version = '1.32'; # a package variable sub Dirname { my $Path = shift; my ($Name, @Temp); @Temp = split (/\\|\//, $Path); # Split on forward or backslash pop @Temp; # Get rid of last element $Name = join ("/", @Temp); return $Name; } # other functions... 1;

Accessing Package Stuff

Using the previous example and assuming the code exists in a file called UnixTools.pm, we can access package variables and functions from our "main" program this way: /usr/local/bin/perl -w use UnixTools; # pulls in definitions from that file $dummy_var = 10; # to be used later # access a package variable print "UnixTools version = $UnixTools::Version\n"; # access a package function print "Root home path = ", &UnixTools::Dirname ($ENV{HOME}), "\n";

Accessing Other Stuff From a Package

Accessing a variable or function that is defined in another package, from a package, needs to be scoped. If a package name is not used, again, the "main" package is the default. So our UnixTools.pm file could have accessed $dummy_var defined in "main" by doing: package UnixTools; # other stuff sub IncDummyMainVar { $main::dummy_var++; } Beginning | Previous | Next
Last Modified: $Date: 1997/05/02 07:17:46 $