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) :)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: goto with anonymous subs
by merlyn (Sage) on Sep 12, 2005 at 15:25 UTC | |
by ysth (Canon) on Sep 12, 2005 at 23:38 UTC | |
by kappa (Chaplain) on Sep 12, 2005 at 16:27 UTC | |
| |
|
Re: goto with anonymous subs
by dragonchild (Archbishop) on Sep 12, 2005 at 15:11 UTC |