
Assocs from linear arrays / assert.pl
Quote:
>>>>>> daviesb writes:
> # Oh, and while I'm crying for the moon - anyone got an assert.pl?
> assert.pl is in the Perl library, but be careful! I've been trying
> to put assertions in my packages in Perl 5 to make them a bit more
> robust, but the following snippet doesn't do what you think:
> [ ... code deleted to save space ... ]
> Apparently, the string in the assertion gets passwd to the assert()
> subroutine and is eval'd in assert's scope - at that point $self
> looks like an undef'd variable. I just wrote an Assert.pm that
> has one wrapper routine - Assert() - and it checks the logical
> value of its parameter, then calls the normal panic() routine
> in assert.pl:
> package Assert;
> require 5.000;
> require Exporter;
> # put it in the package
> require 'assert.pl';
> sub Assert {
> panic("ASSERTION FAILED:") unless $_[$[];
> }
> 1;
Would the following alternative work?
package Assert;
require 5.000;
require Exporter;
require 'assert.pl'; # ... so that &panic() is accessible
$debug = 0;
sub Assert {
if ($debug) {
# Get the caller's package via the 'caller' routine.
my($package) = caller;
eval "package $package";
}
}
1;
(I took the '&panic' line right out of assert.pl and just prepended
'Assert::' ... this line could be tweaked a bit more ... perhaps by
getting rid of '$[').
Quote:
> One thing I haven't found a good way to do is to "compile out"
> assertions if debug is off. What you really need is a macro
> which I haven't though of a way to do in Perl. I'd like 'Assert(exp);'
> to evaluate to '_Assert(exp) if ($debug);' but I don't want to
> run my scripts through cpp. What I've been doing is just writing
> Assert(exp) if ($debug);
> right in my code. A bit ugly, but it gets the job done. Any other
> suggestions?
In my example above, the $debug variable is part of the Assert package.
So, in your code, you could set ...
$Assert::debug = 0;
or
$Assert::debug = 1;
To control whether or not your assertions are virtual no-ops or not.
You still pay the price of a subroutine invocation for each assertion,
however.
Am I missing something, or will my suggestion work?
--
Lloyd Zusman 01234567 <-- The world famous Indent-o-Meter.
To get my PGP public key automatically mailed to you, please
send me email with the following string as the subject:
mail-request public-key