in reply to loop control

What does conditionA say? The basic structure you've got here looks like it should work, so I'm inclined to suspect that conditionA always evaluates as false.

Also, if this is the entire loop (i.e., you're not doing anything else after conditionB's &do_something), you may want to consider rewriting it as

foreach (@tmp) { $do_something if !conditionA && conditionB }

Replies are listed 'Best First'.
Re: Re: loop control
by Galen (Beadle) on May 22, 2002 at 14:56 UTC
    Here is the actual code:
    $out = "<?xml version="1.0" encoding="utf-8"?>"; @tmp = split /</, $out; foreach(@tmp) { if (substr($_, 0, 1) eq "?") { next; } elsif (substr($_, 0, 1) eq "!") { &more_code; } }
    What this is doing is parsing xml. Note that the leading "<" has already been stripped by the split function. The contents of $tmp here are:
    ?xml version="1.0" encoding="utf-8"?>
    If I test whether the condition passes or not by simply printing something like "it passed", then I see this.. so I know it's passing the condition.
      first of all, why not using regexp for parsing the string:
      if (/^\?/) { next; } elsif (/^\!/) { rest of the code ; }
      It's much more clear, efficient and fast.
      secondly, you have a problem with the double quotes inside your string, put single quote as outer quotes.
      and third, after fixing the quotes problem it worked for me, I tried it myself.

      Thanks.

      Hotshot
      Your code as posted (almost) works. After modifying it to
      #!/usr/bin/perl -w use strict; my $out = '<?xml version="1.0" encoding="utf-8"?>'; my @tmp = split /</, $out; foreach(@tmp) { if (substr($_, 0, 1) eq "?") { print "conditionA matched - looping!\n"; next; } elsif (substr($_, 0, 1) eq "!") { print "conditionB matched\n"; } print "End of loop\n"; }
      I get the output
      End of loop conditionA matched - looping!
      as expected. (Note that the split is returning a list of two scalars, not just one: the 0 characters before the < and the n characters after it.)

      Side note: That feels a lot like C. Changing your tests to if (/^\?/) and if (/^!/) would feel perlier. Should work either way, though.

        OK - the problem was what you mentioned, that split is returning two scalars. The first 0 character result is passing through the conditional check and messing things up - it's not the xml declaration, as I thought. By the way, I tried to abbreviate how the string $out was populated and forgot it had quotes in it, so code as posted would have failed (as you and others noticed). The loop works now - thanks much you guys rock! As for the use of substr instead of regex.. well I was mostly doing it for consistency, because substr works so well for isolating pieces of the xml elements. But, efficiency is more important so I'll change it - thanks for the suggestion :)