tags:

views:

148

answers:

3

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.

+6  A: 

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.

Ivan Nevostruev
I'm doing this in Perl5. Is it something new?
Geo
This aspect of Perl6 has been made available in 5.10. It won't work in 5.8 and earlier.
JSBangs
The syntax has been available since 5.8.0 -- it just doesn't do anything very useful in 5.8. It also doesn't do anything very useful in 5.10 ;)
hobbs
my Dog $spot has been around since 5.005 when it was brought in to allow typed lexicals but never really did anything. All it did was try to optimize pseudo-hashes, and if you don't know what pseudo-hashes are consider yourself lucky. These days the only thing "my Class $obj = Class->new" does is tell you the author used to use pseudo-hashes.
Schwern
+11  A: 

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 ...
Greg Bacon
This is the correct answer. Nothing to do with Perl 6. "Restricted hashes" replaced pseudo-hashes, but they're rarely seen these days.
Schwern
A: 

In addition to use by fields, the lexical type is used by the experimental types pragma (available from CPAN).

ysth