Generic const - a non-functional view

Bill Baxter dnewsgroup at billbaxter.com
Thu Jun 26 10:19:42 PDT 2008


Steven Schveighoffer wrote:
> "Bill Baxter" wrote
>> Me Here wrote:
>>> Walter Bright wrote:
>>>
>>> Perl has invariant strings, but they are implicitly invariant
>>>> and so nobody notices it, they just work.
>>>>
>>> Sorry Walter, but thta is simply not the case: Vis:
>>>
>>> [0] Perl> $x = 'x' x 500e6;
>>> [0] Perl> print length $x;;
>>> 500000000
>>> [0] Perl> substr $x, 250e6, 1, 'y';;
>>> [0] Perl> print length $x;;
>>> 500000000
>>> [0] Perl> print substr $x, 250e6-5, 10;;
>>> xxxxxyxxxx
>>>
>>> b.
>> What are you disagreeing with?
>>
>> The fact that they're invariant?
>> Or the fact that nobody notices?
>>
>> I have no idea if they're invariant in perl or not.  But I don't think 
>> your test above is conclusive proof that they're mutable.
> 
> No it's not.  The only conclusive proof comes from observing what happens 
> when you copy strings from one to the other:
> 
> #!/usr/bin/perl
> 
> print "before x\n";
> sleep 20;
> $x = 'x' x 100000000;
> print "initialized x\n";
> sleep 5;
> $y = $x;
> print "copied to y\n";
> sleep 5;
> substr $x, 3, 1, 'y';
> print "did substring\n";
> print substr $y, 0, 5;
> print "\n";
> sleep 5;
> 
> OK, so what does this do?  I set x to a string of 100 million x's, then 
> assign x to y, then replace the 4th character in x with a 'y', then print 
> the first 5 characters of y to see if they changed too (see if x and y 
> reference the same data)
> 
> So what does this output?
> before x
> initialized x
> copied to y
> did substring
> xxxxx
> 
> But this is not yet conclusive proof, we need to watch what happens with 
> memory usage when each step occurs (hence the sleeps).  So using 'top', I 
> observed this:
> 
> before x => mem usage 3k
> initialized x => 191MB (!)
> copied to y => 291MB
> did substring => 291MB
> xxxxx
> 
> So, what it looks like is on assignment, the string is copied, and the 
> editing edits the string in-place.   But I can't really explain why it takes 
> 191MB to store x, where it only takes 100MB to store y.
> 
> So I'd say perl does not have invariant strings.  'course, I'm not a perl 
> hacker, so I don't know if I did this correctly :)

That is a bit more conclusive.  So it appears that what Perl has is not 
invariant strings, but rather mutable strings that are copied on 
assignment so that they can be thought of more or less as value types.

So what happens with function calls?  To keep the illusion of "string is 
a value type" those would need to dup string arguments too.

--bb



More information about the Digitalmars-d mailing list