[sf-perl] aliases, confusion, and me....

Michael Friedman frimicc at gmail.com
Mon Apr 22 16:29:27 PDT 2013


The arrows are optional when you are using multiple subscripts. See 	
	http://stackoverflow.com/questions/2475042/nested-dereferencing-arrows-in-perl-to-omit-or-not-to-omit

The key phrase being, "Subscripts next to subscripts imply references," so you don't need to explain to the parser that you are officially dereferencing, which is what the arrow operator does.

Note that this won't work with $self{foo} instead of $self->{foo} because you only have a single subscript there vs. [0]{foo}.

-- Mike Friedman

On Apr 22, 2013, at 4:19 PM, George Hartzell <hartzell at alerce.com> wrote:

> 
> 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.
> _______________________________________________
> SanFrancisco-pm mailing list
> SanFrancisco-pm at pm.org
> http://mail.pm.org/mailman/listinfo/sanfrancisco-pm



More information about the SanFrancisco-pm mailing list