Now imagine that the LVALUE sub below (with better syntax) was a builtin and the TIESCALAR was invisible--generated automatically by the compiler.
#! perl -slw use strict; package Sensible; sub TIESCALAR { my( $class, $fetch, $store ) = @_; no warnings 'redefine'; *FETCH = *FETCH = $fetch; *STORE = *STORE = $store; bless [], $class; } sub LVALUE (&&) : lvalue { my( $fetch, $validate ) = @_; tie my $lvalue, 'Sensible', $fetch, $validate; $lvalue; } sub new { my( $class, $init ) = @_; return bless \$init, $class; } sub attr : lvalue { my( $self, $start, $len ) = @_; $start ||= 0; $len ||= length ${ $_[ 0 ] }; LVALUE { substr( $$self, $start, $len ) } sub{ warn( 'Bad value' ), return unless $_[ 1 ] =~ m[^[a-z ]+$]; substr( $$self, $start, $len ) = $_[ 1 ]; }; } package main; my $sensible = Sensible->new( 'The quick brown fox jumps over the lazy + dog' ); print $sensible->attr; $sensible->attr( 10, 5 ) = 'green'; print $sensible->attr; $sensible->attr( 20 ) = 'did not see the paint tin'; print $sensible->attr; $sensible->attr( 10, 5 ) = 'ORANGE'; print $sensible->attr; __END__ [ 2:03:26.03] P:\test>425402-2 The quick brown fox jumps over the lazy dog The quick green fox jumps over the lazy dog The quick green fox did not see the paint tin Bad value at P:\test\425402-2.pl line 31. The quick green fox did not see the paint tin
Note how there is no need for a separate tie class for every different validation routine. Just one for scalars, one for arrays, and one for hashes.
Note how all the code is in a single place. And how the validation code has full access to the entire environment of the original sub. No need to pass everything required, it is all available via closure.
One additional keyword and some (a little) extra code generated--by the compiler, not the programmer.
As you can see, you needn't feel silly. I was there a long time ago.
In reply to Re^15: Assignable Subroutines
by BrowserUk
in thread Assignable Subroutines
by dragonchild
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |