Packages provide a namespacing mechanism. Package A can define a function called "output", and package B can define a function called "output", and both packages will see their own output function. Example:
use 5.014;
package A
{
sub stuff { output($_) for qw(1 2 3 4) }
sub output { say "A: @_" }
}
package B
{
sub stuff { output($_) for qw(2 4 6 8) }
sub output { say "B: @_" }
}
package main
{
A::stuff();
B::stuff();
}
Packages are also used for object-oriented programming in Perl. A reference to a variable can become associated with a package (a process known as blessing), after which that reference is considered to be an object. Objects can have method calls performed on them, in which case the method is resolved to a function defined in the package associated with the object. (Or, if there is no such function, potentially a function in a parent class.)
use 5.014;
package C
{
sub foo { say "foo!" }
}
package main
{
my $object = bless []=> 'C';
$object->foo;
}
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
|