in reply to Re: Loop Quandary
in thread Loop Quandary

$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.

Replies are listed 'Best First'.
Re^3: Loop Quandary
by ww (Archbishop) on Nov 22, 2013 at 17:03 UTC

    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.)