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

hello
the next code is to print the match_start and match_end of the pattern 'efg' globally, which will be 4,6 and 10,12 i want to know how i can use "foreach" Loop in this situation instead of the "for" loop and any additional remarks please
thanks
use strict; use warnings; my $string = '0123efg789efg13'; my @matches; my $x='efg'; #the pattern for (0..10000) { if($string =~ /$x/g){ push @matches, $-[0]; push @matches, $+[0]-1; push @matches,"\n"; } else {last} } print "@matches\n";

Replies are listed 'Best First'.
Re: using foreach with a regex
by moritz (Cardinal) on Dec 05, 2008 at 14:47 UTC
    i want to know how i can use "foreach" Loop in this situation instead of the "for" loop
    for and foreach are exact synonyms, so whenever you can one, you can also use the other instead.

    But maybe it's easier to use while ($string =~ /regex/g) { ... } instead of the combination of for and </c> (unless you want to limit the number of possible matches).

      whenever you can one, you can also use the other instead.

      Almost.

      >perl -le"sub for { print 1 } sub foreach { print 2 } &for;" 1 >perl -le"sub for { print 1 } sub foreach { print 2 } &foreach;" 2

      and

      >perl -le"print 'for';" for >perl -le"print 'foreach';" foreach

      This post is not to be taken seriously :)

        whenever you can one, you can also use the other instead.
        Almost.
        Almost. moritz just said that you can use the other, not that you'll get the same result. :-)