Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Making my own control flow structure

by Corion (Patriarch)
on Oct 09, 2006 at 12:25 UTC ( [id://577154] : note . print w/replies, xml ) Need Help??


in reply to Making my own control flow structure

In Perl, there are no custom-made control flow statements like in Lisp, and there are no convenient ways to dump the statements not executed. You can fudge something like it by using eval, in the following way:

sub document_if { my ($cond,$code) = @_; if ($cond) { eval $code } else { print "Not executing:\n"; print $code; print "\n---\n"; }; };

Which you can then clumsily use like this:

document_if( 1 == 0, q{ print "The sky has fallen down.\n"; });

There are a lot of drawbacks to this, as you can't conveniently pass variables into the if block for example. The upside is that the format of the code and the comments will still be output.

The second alternative would be to pass a real code block and then use B::Deparse to get at a string representation:

use strict; use B::Deparse; my $deparse = B::Deparse->new("-p", "-sC"); sub document_if { my ($cond,$code) = @_; if ($cond) { $code->() } else { print "Not executing:\n"; print $deparse->coderef2text($code); print "\n---\n"; }; };

Which you can then use like this, the clumsyness gets pushed into a different corner here:

document_if( 1 == 0, sub{ print "The sky has fallen down.\n"; });

This has the advantage of passing around closures and hence working with local and lexical variables. It has the disadvantage of relying on B::Deparse which doesn't always give you back what you wrote but only gives you back the Artists Rendition.