Hi! Please consider following me on twitter: @hanekomu.
2009年02月14日
Bounds checking with Variable::Magic
Vincent Pit's Variable::Magic is an evil module that allows you to define Perl variable magic in Perl space. I hope to be able to use it for new types of join points in aspect-oriented programming (see Aspect).
Playing around with the module, I thought it could reproduce the effects of
tie() without having to tie objects. For example, let's enhance a
variable so that it can only take values that lie within given lower and upper
bounds.
use Variable::Magic qw(wizard cast); use Carp qw(croak); sub bounds_spell { my ($lower, $upper) = @_; wizard set => sub { my $value = ${$_[0]}; return if $value >= $lower && $value <= $upper; croak "bounds violation: $lower <= $value <= $upper is not true\n"; }; } my $foo; cast $foo, bounds_spell(2,8) or die "wizard FAIL\n"; $foo = 7; # OK $foo += 2; # exception
Setting the variable to 7 works fine, but increasing its value to 9 produces the following error:
bounds violation: 2 <= 9 <= 8 is not true
at test.pl line 15
main::__ANON__('SCALAR(0x800c6c)', 'undef') called at test.pl line 23
posted at: 13:31 | path: /dev | permalink | 0 comments | 0 trackbacks
Comments are closed for this story.
Trackbacks are closed for this story.