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'
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|