In the perlfunc:substr docs, I can find only two references to what it returns:
- Extracts a substring out of EXPR and returns it. (2 and 3 arg version)
and
- This allows you to replace parts of the EXPR and return what was there before. (4-arg version)
The latter isn't really relevant as I'm using the 3-arg version, but it does describe one of the two behaviours I would have expected.
If the 3-arg version as an lvalue were consistant with the 4-arg version, I would expect the replaced part, ('quick ' in my short demo program below) to be returned.
If it was consistant with assignment, then I would expect either the thing being assigned (''), or the result of the assignment ('the brown fox');
What is actually being returned is 'brown '
What is happening is that the substitution (deletion) is being performed using the offset and length, AND THEN the same values are being re-used to extract a return value FROM THE RESULTANT of the assignment.
Whilst I can explain what is happening, using the offset and length *twice* is at least strange. Doing so in order to provide a return value that bears no relationship to either the sub-string specified by the programmer, nor the resultant of the assignment simply make no sense at all.... leastwise, not to me.
#! perl -w
my $s = qq(the quick brown fox);
print substr($s, 4, 6) = '', $/;
__END__
#output
C:\test>191356
brown
C:\test>
With respect to if '' and undef are lvalues, then this is a feature, and not a bug
You rightly point out that the docs say
You can use the substr() function as an lvalue, in which case EXPR must itself be an lvalue.
However,
substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET
The EXPR that must be a LVALUE is the first parameter to substr, not the value being assigned to it.
I can explain what is happening. I still contend that it is neither documented that way nor intuatively expected. Nor, in my opinion, is it sensible.
As it is, I am sufficiently convinced that this is a bug that I will send a perlbug report in along with the bulk of this post minus references about our debate. A link to this entire thread, and allow them to decide whether this is a documentation change, and code fix or simple a vagary of "BrowserUk's missunderstanding".
What's this about a "crooked mitre"? I'm good at woodwork! |