nmerriweather has asked for the wisdom of the Perl Monks concerning the following question:

Currently, i have a conditional state as such:
if ( $action eq 'new' ) { if (!$name) { &print_error; } else { &code_to_create_new(); } }
&code_to_create_new, however, is not a subroutine - its a block of code. i'd like to try and figure out a way to handle the statement as such:
if ( $action eq 'new' ) { if (!$name) { &print_error; ###?### } &code_to_create_new(); }
where ###?### is some perl command that i do not know, that would behave like 'return' does, but affects the parent of the if statement

does this exist?

Replies are listed 'Best First'.
Re: need advice on conditionals
by thedoe (Monk) on Feb 27, 2005 at 21:01 UTC
    You could put the code in a block then last out of it, like this:
    if ($action eq 'new') {{ if (!$name) { &print_error; last; } &code_to_create_new(); }}
    The extra {} is the code block, which the last will exit.
Re: need advice on conditionals
by chromatic (Archbishop) on Feb 27, 2005 at 21:28 UTC

    How about else? What's wrong with either making it a subroutine or stuffing the code in the block of your first example?

Re: need advice on conditionals
by trammell (Priest) on Feb 28, 2005 at 00:10 UTC
    This does what you want:
    if ($action eq 'new') {{ (print_error(), last) unless $name; code_to_create_new(); }}
    ... but it's ugly. Better off to just use if/then/else , for maintainability and clarity.
Re: need advice on conditionals
by Fendaria (Beadle) on Feb 27, 2005 at 21:41 UTC

    It looks like you might be testing argument validity. If so consider die or Carp and catching the error upstream with an eval:

    if ($action eq 'new') { croak "\$name is not defined/set for action == new" unless (defined $name and $name ne ""); # # code to create new # }
    Fendaria
Re: need advice on conditionals
by chas (Priest) on Feb 27, 2005 at 21:09 UTC
    It isn't completely clear to me what you want to do; is &code_to_create_new a subroutine that you want to produce on the fly based on the falsity of $name? If you exhibit the block of code you refer to, that would clarify things. (You don't want a goto, do you?)
    chas