[sf-perl] aliases, confusion, and me....
George Hartzell
hartzell at alerce.com
Mon Apr 22 16:19:58 PDT 2013
Given the following little bit of code.
use strict;
use warnings;
use Test::More;
{
package Poodle;
sub new { return bless {} => __PACKAGE__; }
sub this { my $self = shift; $self->{foo} }
sub that { $_[0]->{foo} }
sub the_other { $_[0]{foo} }
}
my $p = Poodle->new();
$p->{foo} = 10;
is( $p->{foo}, 10, 'reaching into hash worked' );
is( $p->this, 10, 'self works' );
is( $p->that, 10, 'proper dreferencing of alias worked' );
is( $p->the_other, 10, 'HUH?' );
done_testing;
and looking at the methods "this", "that", and "the other".
I consider "this" to be the "right" way to write a method [or
something like this: "my ($self) = @_;" instead of the shift...]
I often see and sometimes use the technique illustrated in "that",
where one directly accesses the alias in the arguments. I thought I
understood the implications of it being an aliases to the value being
passed in.
I was stumped as to why "the_other" works. I figured that it must be
some little subtlety of aliases and argument list and dusty language
corners.
Then I used:
perl -MO=Deparse ~/tmp/ape.pl
to look at how perl's parsing it.
...
sub that {
use warnings;
use strict;
$_[0]{'foo'};
}
sub the_other {
use warnings;
use strict;
$_[0]{'foo'};
}
...
While I now understand why "that" and "the_other" work identically, I
now _do not_ understand why perl's handling them the way that it is.
The same phenomena occurs in a class based on a blessed array ref.
Can anyone explain what's going on?
Thanks,
g.
More information about the SanFrancisco-pm
mailing list