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

The following chunklet parses markup for bolded numbers, and kicks out of the while loop on the first match.   Works fine, lasts 'long time.   But the ++$match seems a bit, uhm, mechanical, maybe?   Might there be smoother ways to facilitate kicking out on the first match?
    cheers,
    Don
    striving toward Perl Adept
    (it's pronounced "why-bick")
my $match = 0; my $pb = HTML::TokeParser->new(\$content); while($pb->get_tag('b', '/b') && $match < 1){ my $tb = $pb->get_text(); if($tb =~ /^\d+$/){ $num = $tb; ++$match; } }

ps - kudos to da loony sleepfree one for his HTML::TokeParser tutorial

Replies are listed 'Best First'.
Re: Exit while loop on first match
by Fletch (Bishop) on Apr 30, 2002 at 15:53 UTC
Re: Exit while loop on first match
by japhy (Canon) on Apr 30, 2002 at 16:09 UTC
    You could use last, or at least an oppositely-named variable:
    my $no_match = 1; while ($pb->... and $no_match) { # ... $no_match = 0; }

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a (from-home) job
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Exit while loop on first match
by erikharrison (Deacon) on Apr 30, 2002 at 17:00 UTC

    The previous suggestions to use last are excellent. A loop label might help:

    MATCH: while { ... last MATCH; }

    Also, I use the phrase "synthectic code" to refer to architectural code: hacks that just exist as a frame to make the algorithm work. This is a phrase stolen from a perl.com article, http://www.perl.com/pub/a/2000/06/commify.html

    Cheers,
    Erik

    Update: Forgot a colon . . . boy is my face red . . .

Re: Exit while loop on first match
by jynx (Priest) on Apr 30, 2002 at 21:16 UTC

    Possibly not the style you wish to go with,

    But in such a situation i would use a bare block loop. Mostly i use them when there are multiple loop modifiers that i want to simplify, and this (sort of) fits that description. In any event, it gets rid of extra variables...

    # note this is completely untested... my $match = 0; my $pb = HTML::TokeParser->new(\$content); { $pb->get_tag('b', '/b'); my $tb = $pb->get_text(); if ($tb =~ /^\d+$/) { $num = $tb; last; } redo; }
    something like that maybe,
    jynx