I know the title sounds funny, but I found this snippet somewhere:
my MyPackage $p1 = MyPackage->new;
What role does the name of the package serve in front of $p1
?
EDIT: I'm running perl 5.10.1
.
I know the title sounds funny, but I found this snippet somewhere:
my MyPackage $p1 = MyPackage->new;
What role does the name of the package serve in front of $p1
?
EDIT: I'm running perl 5.10.1
.
From http://perldoc.perl.org/functions/my.html:
my TYPE EXPR : ATTRS
A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses.
The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of fields pragma, and attributes are handled using the attributes pragma, or starting from Perl 5.8.0 also via the Attribute::Handlers module.
It checks for a package with the same name, and, as of now, is tied to the fields
pragma which helps check for typos in field names.
For example:
package MyPackage;
use fields qw/ foo bar /;
sub new { fields::new(shift) }
Then if you try to run
use MyPackage;
my MyPackage $p1 = MyPackage->new;
print $p1->{notpresent}, "\n";
you get
No such class field "notpresent" in variable $p1 of type MyPackage at ...
In addition to use by fields, the lexical type is used by the experimental types pragma (available from CPAN).