Discussion:
Can I "break out" of an if{} block?
(too old to reply)
u***@DavidFilmer.com
2006-06-08 23:40:44 UTC
Permalink
At any point in a loop, I can "break out" of it with a 'last', or I can
"break out" of a subroutine with a 'return'.

Is there a similar way to easily "break out" of an if{} block (without
a goto)?

Thanks!
--
David Filmer (http://DavidFilmer.com)
John W. Krahn
2006-06-08 23:57:57 UTC
Permalink
Post by u***@DavidFilmer.com
At any point in a loop, I can "break out" of it with a 'last', or I can
"break out" of a subroutine with a 'return'.
Is there a similar way to easily "break out" of an if{} block (without
a goto)?
Sure, just put a loop inside the if block:

if ( $expression ) { {
last if $oops;
} }


John
--
use Perl;
program
fulfillment
Tad McClellan
2006-06-09 00:41:10 UTC
Permalink
Post by u***@DavidFilmer.com
At any point in a loop, I can "break out" of it with a 'last', or I can
"break out" of a subroutine with a 'return'.
Is there a similar way to easily "break out" of an if{} block (without
a goto)?
Yes, by nesting another if:

if ( $something ) {
# do this always
if ( ! $want_to_last ) { # unless ( $want_to_last ) is "nicer"
# do this when not "lasting"
}
}
--
Tad McClellan SGML consulting
***@augustmail.com Perl programming
Fort Worth, Texas
Ben Morrow
2006-06-09 00:45:45 UTC
Permalink
Post by u***@DavidFilmer.com
At any point in a loop, I can "break out" of it with a 'last', or I can
"break out" of a subroutine with a 'return'.
Is there a similar way to easily "break out" of an if{} block (without
a goto)?
Any block (except for the pseudoblocks which are part of if{}, else{},
do{} &c.) is treated as a loop which loops once. So just add another set
of braces and use 'last':

if (1) {{
#...
last if #...
#...
}}

Ben
--
All persons, living or dead, are entirely coincidental.
***@tiscali.co.uk Kurt Vonnegut
Continue reading on narkive:
Loading...