Perl 'package'

extern: index | reference
intern: package | sample | hexer | __PACKAGE__ | end

package - http://perldoc.perl.org/functions/package.html

package NAMESPACE;

The perl 'package' declaration declares the compilation unit as being in the given 'NAMESPACE', as contained in __PACKAGE__. The scope of the package declaration is from the declaration itself through the end of the enclosing block, file, or eval (the same as the my operator). All further unqualified dynamic identifiers will be in this namespace.

You can switch into a package in more than one place; it merely influences which symbol table is used by the compiler for the rest of that block. You can refer to variables and file handles in other packages by prefixing the identifier with the package name and a double colon: $Package::Variable . If the package name is null, the main package as assumed. That is, $::sail is equivalent to $main::sail (as well as to $main'sail , still seen in older code).

top -|- index -|- samples


Sample

Some sample code using 'package' to declare a 'Hexer' namespace, then switch back to 'main' to use this package...

code:

#!/usr/bin/perl -W
# NAME: package.pl
# AIM: Simple use of 'package' declaration
use strict;
use warnings;
####################################
package Hexer;
####################################
sub new {
    my($class) = @_;
    my $str = "";
    bless \$str, $class;
}
sub toHex {
   my ($self,$str) = @_;
   my $len = length($str);
   my @a = unpack ("C$len", $str);
   my $s = "";
   for (@a) {
       $s .= sprintf ("%02x ", $_);
   }
   $s;
}
######################################
package main;
######################################
my $cc = "ABC \n";
my $a = new Hexer;
my $hex = $a->toHex($cc);
print "hex $hex\n";
######################################
# eof - package.pl

output:

hex 41 42 43 20 0a

Note the TEMPLATE used for the 'unpack (TEMPLATE, EXPR)' is "C$len", which is an 'unsigned character (octal) value' array - see pack documentation for the possible TEMPLATES - for the length of the string. And that's it ...

top -|- index -|- samples


__PACKAGE__

This is a reserved global value, containing the current 'namespace', and then a function, dispSymbols(), to display the 'symbols' defined in a 'package'...

code:

#!/usr/bin/perl
use strict;
use warnings;
my $pack = __PACKAGE__;
print "Show defined symbols in package [$pack]\n";
sub dispSymbols {
    my ($hashRef) = shift;
    my (%symbols);
    my (@symbols);
    %symbols = %{$hashRef};
    @symbols = sort(keys(%symbols));
    foreach (@symbols) {
        printf("%-10.10s| %s\n", $_, $symbols{$_});
    }
}
my $sym = '\%'.$pack.'::';
dispSymbols(eval $sym);

output:

Show defined symbols in package [main]
         | *main::
↕         | *main::↕
↕E_TRIE_MA| *main::↕E_TRIE_MAXBUF
↨ARNING_BI| *main::↨ARNING_BITS
↑         | *main::↑
"         | *main::"
$         | *main::$
/         | *main::/
0         | *main::0
@         | *main::@
ARGV      | *main::ARGV
ActivePerl| *main::ActivePerl::
BEGIN     | *main::BEGIN
CORE::    | *main::CORE::
Carp::    | *main::Carp::
DB::      | *main::DB::
DynaLoader| *main::DynaLoader::
ENV       | *main::ENV
INC       | *main::INC
... etc ... etc ...
dispSymbol| *main::dispSymbols
main::    | *main::main::
mro::     | *main::mro::
re::      | *main::re::
stderr    | *main::stderr
stdin     | *main::stdin
stdout    | *main::stdout
strict::  | *main::strict::
utf8::    | *main::utf8::
version:: | *main::version::
warnings::| *main::warnings::

More on the symbol tables and can be found at - http://affy.blogspot.com/p5be/ch15.htm

Care should be taken when using these 'Special Literals', like __PACKAGE__, __FILE__, __LINE__!, They may be used only as separate tokens; they will not be interpolated into strings. And, if there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value. Example :-

code:

package Illumination;
use strict;
use warnings;
use Data::Dumper;
my %hash;
my $pack = __PACKAGE__;
my $line = __LINE__;
my $file = __FILE__;
$hash{$pack}{$file}{$line} = "Mo Mo";
$hash{__PACKAGE__}{__FILE__}{__LINE__} = "Mu Mu";
print Dumper \%hash;

output:

$VAR1 = {
              'Illumination' => {
                                  'temp.pl' => {
                                                 '7' => 'Mo Mo'
                                               }
                                },
              '__PACKAGE__' => {
                                 '__FILE__' => {
                                                 '__LINE__' => 'Mu Mu'
                                               }
                               }
            };  

top -|- index -|- samples

Two other 'Special Literals' are __END__ and __DATA__


from : http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html

Some interesting examples, showing 'scope' of variables...

code:

#!/usr/bin/perl
# not strict clean, yet, but just wait
# ie can NOT 'use strict;'!
$global = "I'm the global version";
sub show_me {
        my $tag = shift;
        print "$tag: $global\n"
}
sub lexical {
        my $global = "I'm in the lexical version";
        print "In lexical(), \$global is --> $global\n";
        show_me('From lexical()');
    }
sub localized {
        local $global = "I'm in the localized version";
        print "In localized(), \$global is --> $global\n";
        show_me('From localized');
    }
    show_me('At start');
    lexical();
    localized();
    show_me('At end');

output:

At start: I'm the global version
    In lexical(), $global is --> I'm in the lexical version
    From lexical(): I'm the global version
    In localized(), $global is --> I'm in the localized version
    From localized: I'm in the localized version
    At end: I'm the global version

And there is more... from vartypes.pl to HTML.

code:

#!/usr/bin/perl
package Foo;
@n      = 1 .. 5;
$string = "Hello Perl!\n";
%dict   = ( 1 => 'one' );
sub add { $_[0] + $_[1] }
foreach my $entry ( keys %Foo:: ) {
        print "-" x 8, " Name: [$entry]\t";
        print "scalar is defined\n" if defined ${$entry};
        print "array  is defined\n" if defined @{$entry};
        print "hash   is defined\n" if defined %{$entry};
        print "sub    is defined\n" if defined &{$entry};
    }

output:

-------- Name: [n]      array  is defined
    -------- Name: [add]    sub    is defined
    -------- Name: [string] scalar is defined
    -------- Name: [dict]   hash   is defined

And from typeglob-name-package.pl to HTML.

code:

#!/usr/bin/perl
package Foo;
$foo = "Some value";
$bar = "Another value";
    who_am_i( *foo );
    who_am_i( *bar );
sub who_am_i {
        local $glob = shift;
        print "I'm from package [" . *{$glob}{PACKAGE} . "]\n";
        print "My name is ["       . *{$glob}{NAME}    . "]\n";
    }

output:

I'm from package [Foo]
    My name is [foo]
    I'm from package [Foo]
    My name is [bar]

And a tricky typeglob assignment from typeglob-assignment.pl to HTML.

code:

#!/usr/bin/perl
$foo = "Foo scalar";
@foo = 1 .. 5;
%foo = qw(One 1 Two 2 Three 3);
sub foo { "I'm a subroutine!"; }
    *bar = *foo;  # typeglob assignment
print "Scalar is <$bar>, array is <@bar>\n";
print 'Sub returns <', bar(), ">\n";
$bar = 'Bar scalar';
@bar = 6 .. 10;
print "Scalar is <$foo>, array is <@foo>\n";

output:

Scalar is <Foo scalar>, array is <1 2 3 4 5>
    Sub returns <I'm a subroutine!>
    Scalar is <Bar scalar>, array is <6 7 8 9 10>

Zute...

top -|- index -|- samples


EOF - perl_package.htm

checked by tidy  Valid HTML 4.01 Transitional