develooper Front page | perl.perl5.porters | Postings from August 2001

Want: generalised context

Thread Next
Robin Houston
August 21, 2001 05:05
Want: generalised context
Message ID:
As some of you know, I maintain a CPAN module called Want.

It was inspired by Damian's RFC21 for Perl 6, but has some significant
differences as well.

One feature - which I call ASSIGN context - is relevant to the debate
about the behaviour of lvalue subroutines. Suppose, for the sake of
definiteness, that you want to write a subroutine which takes a string
and reverses it, and which (like substr) can also be used lvaluably.

 sub backwards :lvalue { ... }

 backwards(my $foo) = "robin";         # $foo eq 'nibor'
 backwards( substr($foo, 3) ) = 'elb'; # $foo eq 'nibble'

This example isn't vastly useful, but you can see that it's an
interesting programming model.

Using ordinary Perl 5.6 (say), the only way to implement this
is to write a TIESCALAR class whose objects keep a reference
to the argument and whose STORE method does the actual reversal.

 package Reversi;
   my ($class, $stringref) = @_;
   bless $stringref, $class;
 sub FETCH {
   my ($self) = @_;
   return scalar reverse $$self;
 sub STORE {
   my ($self, $val) = @_;
   $$self = reverse $val;

 package main;
 sub backwards :lvalue {
   tie my $x, 'Reversi', \$_[0];

That wasn't *too* hard, but it could certainly be easier...
Now with Want, it could be written like this:

 use Want;
 sub backwards :lvalue {
    if (want('LVALUE ASSIGN')) {
        $_[0] = reverse want('ASSIGN');
        return undef;
    else {
        return scalar reverse $_[0];

At the very least, you now have somewhere to point the next person
who asks for this feature to be added to the core :-)


ps. Suggestions and criticism gratefully received.

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