Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333] : superdoc . print w/replies, xml ) Need Help??

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.


In reply to Re: Making my own control flow structure by Corion
in thread Making my own control flow structure by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.