develooper Front page | perl.perl5.porters | Postings from April 2015

Re: Is there a clever way to null out non-void subs?

Thread Previous | Thread Next
From:
Aristotle Pagaltzis
Date:
April 22, 2015 03:30
Subject:
Re: Is there a clever way to null out non-void subs?
Message ID:
20150422033015.GA78559@plasmasturm.org
Hi Tom,

does this code fulfil your requirements?

    use 5.016;
    use warnings;

    package Assert;
    use Keyword::Simple;

    sub import {
        my $class = shift;
        my $pkg = caller;
        my $debug = @_ ? $_[0] : 1;
        Keyword::Simple::define ASSERT => sub {
            my ( $ref ) = @_;
            substr( $$ref, 0, 0 ) = $debug
                ? 'die "Failed assertion" unless'
                : '0 and die';
        };
    }

    1;

This injects source text, which is dicey. However, it hooks the parser
to find the injection point, so it’s safe in a way that source filters
are not. (Refer to the Keyword::Simple docs for the specifics and the
caveats and all that.)

If you need something simpler and safer and more compatible then the
best you can do is likely

    do_whatever if DEBUG;

which is how everyone does this. (If the constant is true then this gets
constant-folded to be unconditional, and if false then the whole shebang
gets folded away wholesale.) (I hope I’m not trying to educate you about
stuff you knew plenty well already. I would have assumed that you do but
given your mail, maybe you do not, in which case, there you go.)

Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>

Thread Previous | 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