http://www.perlmonks.org?node_id=646406


in reply to Re: my My $my;
in thread my My $my;

Thanks for the replies, I figured it out now, I think.

Saying

my My $my
indeed tells the compiler that $my should be a My object. This information is not used for type-checking, however (neither at run-time nor at compile time). It is currently only used to make use of the fields pragma, which lets you define your class' fields:
# compile error $my->{no_such_field} ++;
In addition to checking the spelling of field names, you get the improved performance of having the hash access turned into an array/pseudo-hash access (On the other hand, pseudo-hashes seem to be evil, the docs warn about their imminent removal from Perl).
use strict; { package My; use fields qw[ one ]; sub new { return fields::new(shift); } } my My $my = new My; $my->{one}++;
b-deparses to
package My; sub BEGIN { use strict 'refs'; require fields; do { 'fields'->import('one') }; } sub new { use strict 'refs'; return fields::new(shift @_); } package main; use strict 'refs'; {;}; my $my = 'My'->new; ++$$my[1]; ## <--- array access