Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

pos, substr, and memory effects

2 views
Skip to first unread message

David Manura

unread,
Apr 19, 2004, 11:59:52 PM4/19/04
to perl5-...@perl.org
The output for the below program appears odd:

===========================
use strict;

my $x = "abc";
my $y = "xyz";

for my $n (0..1) {
my $xr = $n ? \$y : \$x;
my $yr = \substr($$xr, 0);

$$yr =~ /./g;

print '$xr=', "$xr [$$xr]\n";
print '$yr=', "$yr [$$yr]\n";
print 'pos($x)=', pos($x), "\n";
print 'pos($y)=', pos($y), "\n";
print 'pos($$xr)=', pos($$xr), "\n";
print 'pos($$yr)=', pos($$yr), ($n and " <-- why???" or ''), "\n";
}
===========================

Here's the output:

===========================
$xr=SCALAR(0x1013d0dc) [abc]
$yr=LVALUE(0x10140e54) [abc]
pos($x)=
pos($y)=
pos($$xr)=
pos($$yr)=1
$xr=SCALAR(0x1013d0e8) [xyz]
$yr=LVALUE(0x10140e54) [xyz]
pos($x)=
pos($y)=
pos($$xr)=
pos($$yr)=2 <-- why???
===========================

This behaves identically under Perl 5.61, 5.8.0-5.8.3 (x86 Windows, Linux, and
Cygwin).

Note in particular that $yr has the same memory address (but different contents)
in the two iterations of the loop so that pos($$yr) is oddly retained across
iterations.


Now, here's something even more interesting, but it looks to be a bug that has
already been patched since 5.8.0. Consider this code:

===========================
use strict;

sub extract
{
my $textref = \$_[0];

print "pos=", pos($$textref), "\n";

# works fine if the following line is commented out.
pos($$textref) = pos($$textref);

$$textref =~ m/./gc;

# different results if the following line is uncommented.
#$$textref;
}

for my $n (0..1) {
my $s ='abc';

() = extract(substr($s, 0), '{}');
}
===========================

Cygwin Perl 5.8.2, Linux Perl 5.8.1/5.8.3, ActivePerl 5.6.1, and self-compiled
msvc6 Perl 5.8.2 output this:

===========================
pos=
pos=
===========================

ActivePerl 5.8.0 and a self-compiled msvc6 Perl 5.8.0 output this:

===========================
pos=
pos=3
===========================


--david manura, dm.list[-at-]math2.org

Yitzchak Scott-Thoennes

unread,
Apr 20, 2004, 5:17:08 AM4/20/04
to perl5-...@perl.org

My first reaction is that putting the g magic on the PVLV is the right
thing to do, but when the targ is reused, any magic needs to be
removed (or just bypass the targ if it has magic).

0 new messages