Don't worry -- that's not a loop. The doing() construct means "do this once", as opposed to looping().use Loop::Watch; my $x = 2; ensure { $x > 0 } watching($x), doing { # all your code centered around $x here };
There are probably some assertion modules out there, and mine is one such module.
As for your question about passing the value, the answer is to not use tie(). "Huh?" Well, don't have your interface use tie(). Have it use some auxiliary function that calls tie() with the appropriate duplicated value. Here's how I would write the application.
Above is the module responsible for keeping track of the scalar. Now is the code that uses it.package Tie::Scalar::Watch; use Carp; use strict; # rich man's Exporter ;) # this just puts 'watch()' in the caller's namespace sub import { my $pkg = caller; no strict 'refs'; *{ $pkg . "::watch" } = \&watch; } sub TIESCALAR { my ($class, $val, $rule) = @_; my $self = bless [ undef, $rule ], $class; $self->STORE($val); return $self; } sub FETCH { $_[0][0] } sub STORE { my ($self, $val) = @_; return $self->[0] = $val if $self->[1]->($val); croak "Value $val is out of bounds"; } sub watch (&$) { tie $_[1], __PACKAGE__, $_[1], $_[0]; } 1;
That code doesn't run forever -- it prints 10, 9, 8, 7, and 6, and then dies with Value 5 is out of bounds at ... line 11.use Tie::Scalar::Watch; # imports 'watch' my $x = 10; watch { $_[0] > 5 } $x; # $x is now transparently tied! # and you thought tying was transparent already! while (1) { print "$x\n"; $x--; }
If you want to know how to write the code such that you can say watch { $foo > 5 } $foo instead of using the "ugly" $_[0] notation, here's how:
Sneaky, no? That's all for now. I hope this helps you out.sub STORE { my ($self, $val) = @_; $self->[0] = $val; $self->[1]->() ? return $val : croak "Value $val is out of bounds"; }
_____________________________________________________
Jeff[japhy]Pinyan:
Perl,
regex,
and perl
hacker.
s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;
In reply to Re: two-part question about tied variables
by japhy
in thread two-part question about tied variables
by seattlejohn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |