Mailing List Archive

darned $_ and /g
I have not been having a good time with this /g thing lately.
Here's another forever loop:

$_ = 'qwerty';
while ( /(.)/g ) { f($1) }
sub f {
local $_ = shift;
print "got $_\n";
}

--tom
Re: darned $_ and /g [ In reply to ]
On Sat, 7 Oct 1995, Tom Christiansen wrote:

> I have not been having a good time with this /g thing lately.
> Here's another forever loop:
>
> $_ = 'qwerty';
> while ( /(.)/g ) { f($1) }
> sub f {
> local $_ = shift;
> print "got $_\n";
> }

This is solvable either of two ways:


$_ = 'qwerty';
while ( /(.)/g ) { f($1) }
sub f {
my($p)=pos($_); {
local $_ = shift;
print "got $_\n";
}; pos($_) = $p;
}

Or:

$a = 'qwerty';
while ( $a =~ /(.)/g ) { f($1) }
sub f {
my $a = shift;
print "got $a\n";
}

It's pretty clear that local() isn't preserving pos() status.

> --tom

--
Kenneth Albanowski (kjahds@kjahds.com, CIS: 70705,126)
Re: darned $_ and /g [ In reply to ]
: It's pretty clear that local() isn't preserving pos() status.

Already in the database as NETaa13417, "Semantics of pos() vs
local()". You'll note it's in a Postponed state. Fixing it would,
unfortunately, induce a high overhead in local(). Magic travels with
the variable name rather than the value, so for instance, when you say
local($/), you really are undefining the record separator (temporarily).
There might be a way of restoring pos magic, but it would probably
entail running down the list of magics and sending some of them with
the name, and others with the saved value. This wouldn't be cheap.

Hmm. There may be another way, differenting based on the value of
"localizing". Lemme think about that some more. There are other kinds
of magic with similar difficulties. I already did something like that
with tainting. It's vaguely possible that if I fix this you might even
be able to say things like:

local substr($foo,0,1) = "bar";

But maybe not for 5.002. I already postponed it once.

Larry