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

Want: generalised context

Thread Next
From:
Robin Houston
Date:
August 21, 2001 05:05
Subject:
Want: generalised context
Message ID:
20010821130520.A23179@puffinry.freeserve.co.uk
As some of you know, I maintain a CPAN module called Want.
http://search.cpan.org/doc/ROBIN/Want-0.04/Want.pm

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;
 sub TIESCALAR {
   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];
   $x;
 }


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 :-)

 .robin.

ps. Suggestions and criticism gratefully received.

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About