develooper Front page | perl.perl5.porters | Postings from June 2013

postfix dereference syntax

Thread Next
Ricardo Signes
June 27, 2013 01:59
postfix dereference syntax
Message ID:

Perl 5's references are fine, but sometimes dereferencing them is not.  We end
up switching between postfix and circumfix syntax to dereference structures.

  push @{ $x->{foo}->[0]->m }, $y;


In 5.14, an experimental feature was added to avoid this in some contexts:

  push    $x->{foo}->[0]->m  , $y;

In other contexts, it (obviously) can't help:

  push @y, @{ $x->{foo}->[0]->m };

  subroutine( @{ $x->{foo}->[0]->m } )

We need that circumfix deref on the right hand side of the push to indicate we
want the arrayref contents, not the arrayref.  In the subroutine call, there's
really no context for picking how or whether to dereference, so we have to do
it intentionally, and that means circumfix.

There have also been questions about the ambiguity of auto-deref.  I think
the current situation is not great, but it could be better by restoring some of
the initial design of autoderef.  When disambiguation is needed (because we
want "each @{ $x->{foo}->[0]->object_with_deref_overloads }"), though, we're
back to circumfix.

We can add postfix syntax for dereferencing to work in *all* places that we
might dereference, creating a construct that is clearly syntactically an array
(or hash, etc.) when needed.

  push $x->{foo}->[0]->m->@*, $y;

  push @y, $x->{foo}->[0]->m->@*;

  subroutine( $x->{foo}->[0]->m->@* )

  print $delivery->{email}->body_string_ref->$*;

If we want the two forms to be really of equivalent value, we'll also need to
be concerned with:

  print "Things: $aref_of_things->@*"

...which gets into less clearly-introduceable behavior.

Finally, do we need to enable postfix slices?  I think that if we can, we
should.  I think the syntax is free.

  say for $href->{aref}->@[ 0, 2, 4 ];

  say for $aref->[ $h_idx ]->@{ qw(foo bar baz) };

I think we have a few options for the specific tokens to put after that last
arrow.  I think $* and @* and so on work well.  Replacing the splat with a
colon has been suggested as well.  The point here is to provide the feature.
It's not about reducing total punctuation.  This is Perl, and we must embrace
our punctuation!  It's about simplifying the reading of code by allowing it to
be read and written linearly.


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About