SPUG: refs to substrings contain lvalues

Aaron W. West tallpeak at hotmail.com
Fri Jul 30 22:50:37 CDT 2004


I read the answers to that perlmonks programming problem someone posted, and
learned that a
reference to a substring contains an LVALUE.

$ perl -le '$x="stargazing";
 $y=\substr($x,0,4);
 print $y;
 $$y=" sun";
 print $x'

Output:
LVALUE(0x10101570)
 sungazing

So, storing a reference to a substring allows writing to that substring. The
substring is effectively aliased to a new variable. If you write a longer or
shorter string to the substring, the base string grows or shrinks.

$ perl -le '$x="stargazing";
$y=\substr($x,0,4);
print $y;
$$y=" sunflowers";
print $x'

Output:
LVALUE(0x10101570)
 sunflowersgazing

$ perl -le '$x="stargazing";
$y=\substr($x,0,4);
print $y;
$$y="sun";
print $x;
print $$y
use Data::Dumper;
print Dumper($y)'

Output:
LVALUE(0x10101570)
sungazing
sung
cannot handle ref type 9 at /usr/local/lib/perl5/5.8.4/cygwin/Data/Dumper.pm
line 158.

Dumper doesn't know how to handle refs to substrings, apparently.

Such aliasing is also possible with \vec().

$ perl -le '$x="aaron"; vec($x,5,1)=0; print $x'
Aaron
$ perl -le '$x="aaron"; $rv = \vec($x,5,1); $$rv = 0; print $x'
Aaron

So it's possible to alias any individual bit or sequential sequence of bits
to a variable (though it has to be a reference)!

Ain't perl neat.



More information about the spug-list mailing list