Hello, fellow monks!

Quite often we need to check some conditions right after subroutine entry. Maybe such pattern is actually too elementary and boring to be called a "pattern" in the Gang of Four sense. But let it be so for now. Some conditions are vital to continue, so unless they're met we just scream and return.

We usually do something like this:

sub really_big_form { my $q = shift; my $sid; unless ($sid = $q->param('session')) { print_error('Get a session, loser'); return; } unless ($session_vars{$sid}{new_style}) { respawn_session($sid); print_error('Old-style sessions are not cool, you are upgraded, go check your settings right now'); return; } # ... }

There're LOTS of ways (both as written practices and as ready CPAN modules) to reduce coding redundancy by creating some pre/post-condition lists and automatically evaluating them on subroutine entry. I've recently found out an interesting way to cut those returns. Maybe that's common knowledge, but I thought it will fit Meditation section.

sub really_big_form { my $q = shift; my $sid = $q->param('session') or goto sub { print_error('Get a session, loser'); }; $session_vars{$sid}{new_style} or goto sub { respawn_session($sid); print_error('Old-style sessions are not cool, you are upgraded, go check your settings right now'); }; # ... }

goto &sub is a well-known way of doing several certain things like calling newly-created subs from AUTOLOAD or jumping to "inherited" parent methods. It can also be used to "switch" to inline anonymous subs (or any coderef) as it turned out -- this is even a documented feature.

I've used goto $handler several times with dispatch tables but never goto sub {}. It looks funny (and therefore it's good) :)

--kap

In reply to goto with anonymous subs by kappa

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.