codescracker


perl

Perl Packages Modules



« Previous Tutorial Next Tutorial »


Perl Packages

The package statement in perl basically switches the current naming context to a specified namespace. Therefore:

Here is an example, having main and Foo packages in a file. Here, __PACKAGE__, special variable used to print the package name:

#!/usr/bin/perl

# following is the main package

$i = 1; 
print("Package name = " , __PACKAGE__ , " $i\n"); 

package Foo;

# following is the Foo package

$i = 10; 
print("Package name = " , __PACKAGE__ , " $i\n"); 

package main;

# following is again the main package

$i = 100; 
print("Package name = " , __PACKAGE__ , " $i\n"); 
print("Package name = " , __PACKAGE__ ,  " $Foo::i\n"); 

1;

When the above perl code is executed, it will produce the following output:

Package name = main 1
Package name = Foo 10
Package name = main 100
Package name = main 10

Perl Modules

Module in perl, is basically a reusable package defined in the library file whose name is the same as the package's name along with .pm extension. Here is an example:

#!/usr/bin/perl

package Foo;
sub bar
{ 
   print "Hello $_[0]\n" 
}

sub blat
{ 
   print "World $_[0]\n" 
}
1;

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test