in reply to regex 1st match only

That code doesn't compile.

Assuming it did compile, one way to do what you're asking is this:

while( CONDITION_A ) { if( CONDITION_B ) { # DO SOMETHING last; # Exits loop immediately. } }

The last keyword is discussed in perlsyn and last. Some languages would call it break.

While I'm not among them, there are purists of structured programming who would advise against such short circuits as next, and last. They would prefer you jump through hoops such as this:

my $found = 0; while( CONDITION_A && ! $found ) { if( CONDITION_B ) { # DO_SOMETHING $found = 1; } else { # BLAH BLAH } }

In specific cases, such hoops may be able to be rendered less wordy. Either way, it's all just a matter of programming. ;)


Dave

Replies are listed 'Best First'.
Re^2: regex 1st match only
by Laurent_R (Canon) on Oct 28, 2014 at 20:05 UTC
    While I'm not among them, there are purists of structured programming who would advise against such short circuits as next, and last.

    Those purists probably don't really understand what structured programming is really about and want to make it a bureaucratic straight jacket.

    I remember that one of my CS professors once chastised me for having written a function or procedure (I can't remember which language it was, most probably either C or Pascal) in which I was returning early out of the function if a certain condition was met (or not met, whatever), saying me that this was a form of hidden goto (he had introduced Dijkstra's famous "Goto considered harmful" piece just a week or two before). I still received a fairly good mark, but I really felt at the time it was a ridiculous point.

    I was quite happy, years later, to read somewhere in the Camel Book that programming is often building a decision tree and that it makes sense to discard early special cases, rather than having a deeply nested if/then/elsif/else conditional. Quite often, using next or last can also improve significantly the performance and the readability.

    I would strongly suspect that Perl is not the right language for such purists. Let them write ten times more code-lines with A*a or Ja*a. (OK, sorry, I don't want to introduce a language flame war, but I replaced yesterday a 1500++ lines shell script with less than 20 lines Perl script, and it works better).

      Our objective usually is to develop correct code at a minimum lifecycle cost. Structured programming is a great tool. It should never be allowed to interfere with the objective.
      Bill
        ++, Bill.