develooper Front page | perl.perl5.porters | Postings from July 2011

Why views are useful, and why their syntax doesn't matter much

Thread Next
Chip Salzenberg
July 3, 2011 15:26
Why views are useful, and why their syntax doesn't matter much
Message ID:
I was asked in another forum why, in my view patch, I didn't reuse the
mechinisim that "foreach" uses to create aliases.  This is a common question
so I'll answer it here as well.

A simple alias (or, synonymously, a "binding") is not a difficult trick.
 foreach() has done it forever, Data::Alias does it for more cases.  It
could be normalized into the language in a few ways.  For one example, \$a,
\@a, \%a, and \&a could be made lvalues whether they're lexical or not.  So
e.g. the behavior of
   foreach ($x) {...}
could be replicated with
   { local \$_ = \$x; ... }
The point I'm making is that simple, usable aliasing requires no change to
how SVs work, only perhaps some small new magic involving LVALUEs.
 Similarly, if a Perl6-style := operator is introduced for binding, then
LVALUE hackery is not required; instead, the lexer(maybe), grammar, and new
opcode(s) will do the work.  And even in this case, the way SVs work need
not change at all.


What views offer are the ability to add semantics - filters - to the
aliasing.  The only current use case, perhaps the only ever, is adding
read-only-ness.  So after something like

   view const $v, $original;

or whatever the syntax might be, then:

   \$v == \$original         # true
   $original=1; print $v     # "1"
   $v=1                      # throws exception

This is mostly useful for subroutine parameters, and so the primary
consumers of the feature will be the function signature implementors.  This
is also why the syntax is not very important; end users will seldom type it.
 The only visibility that end users might be interested in is a hypothetical
viewed() operator to reach through a view to the real value.

For this reason I expect the first merged code for views will not have any
syntax at all, but only an XS module with some utility functions.

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