in reply to Loop Quandary

perldoc perlsyn:
"while" repeats the statement *while* the condition is true.
$InfStr() is always true.

Replies are listed 'Best First'.
Re^2: Loop Quandary
by oiskuu (Hermit) on Nov 22, 2013 at 15:40 UTC
    $InfStr() is not the while condition here.

    Update:
    The reason first loop ends is because $str stores the necessary magic for m//g.
    Second loop is infinite since InfStr() returns a fresh value each iteration.

    $ perl -MDevel::Peek -e'(my $x = "ababa") =~ m/a/g; print Dump($x);' SV = PVMG(0x7b65a0) at 0x786680 REFCNT = 1 FLAGS = (PADMY,SMG,POK,pPOK) IV = 0 NV = 0 PV = 0x778780 "ababa"\0 CUR = 5 LEN = 8 MAGIC = 0x780ee0 MG_VIRTUAL = &PL_vtbl_mglob MG_TYPE = PERL_MAGIC_regex_global(g) MG_LEN = 1

    Returning a reference from the sub can work around the problem:

    my $x = "ababa"; sub foo { \$x; } print join " ", @-, @+ while ${foo()} =~ m/a/g;

    I hope this explains things a little bit better.

      Before the update oiskuu says in the node above that $InfStr "is not the while condition here. (emphasis supplied)"

      Strictly speaking that's true; in fact $InfStr isn't a condition at all, but that misses the point.

      But that's not what my preceeding node says (omitting the detail that the condition is while(InfStr() =~ /(a)/g){).

      The condition is InfStr() =~ /(a) and it IS always true because the sub always returns a value in which the test is true (My update: And that's pretty much the explanation espoused in oiskuu's "Update" above. And, oh yes, I added the initial phrase in this node to make the thread more readable.)