Often people expect these to work alike. Even when they realize that the 4-arg version (as documented) returns the replaced portion of the string while the 3-arg version returns part of the new string, some discard the evidence of their eyes and think that the 3-arg version returns the string being assigned. (Past discussions of this: 108532, 158756, 191334, 298173; also see perl bugs #16834, #24069, and #24346.)$ perl -wl $x = "abc"; print "4-arg: ", substr($x="abc", 1, 1, ""); print "3-arg: ", substr($x="abc", 1, 1) = ""; __END__ 4-arg: b 3-arg: c
What's really happening is fairly simple to describe: the special magic value returned by substr is used twice, once by the assignment to replace 1 character at position 1, and once by print to get the 1 character now at position 1.
A patch to perl is being considered to adjust this behaviour to be more DWIMy. It updates the length stored in the magic value when ever it is set, so substr(...)="foo" has the appearance of returning the value assigned.
What do you all think? Should this be changed in 5.8.3? In 5.10.0? Never? In one of the threads above, leaving it unchanged is passionately defended by one monk, on the grounds of backward compatibility and perl6 being the proper place to break this kind of thing. On the other hand, the current behavoiur generates a lot of questions. On the third hand, the questions mostly take the form of expecting substr(a,b,c)="" to return the same as substr(a,b,c,""), which isn't really possible. On the fourth hand, this still works with the proposed change :)
Update: I think my description of the change is inadequate. Basically, lvalue substr returns a magic SV that acts as if was tied with this access:
(but tie magic isn't actually used). The change is equivalent to adding a $self->{length} = length($new) at the end of STORE.sub FETCH { my $self=shift; substr($self->{string}, $self->{length}, $ +self->{offset}) } sub STORE { my ($self, $new) = @_; substr($self->{string}, $self->{len +gth}, $self->{offset}, $new) }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: lvalue substring oddities
by Zaxo (Archbishop) on Nov 12, 2003 at 04:22 UTC | |
by ysth (Canon) on Nov 12, 2003 at 05:02 UTC | |
by ysth (Canon) on Nov 12, 2003 at 16:58 UTC | |
Re: lvalue substring oddities
by BrowserUk (Patriarch) on Nov 12, 2003 at 09:11 UTC | |
by Abigail-II (Bishop) on Nov 12, 2003 at 09:31 UTC | |
by BrowserUk (Patriarch) on Nov 12, 2003 at 14:08 UTC | |
by Abigail-II (Bishop) on Nov 12, 2003 at 14:35 UTC | |
Re: lvalue substring oddities
by pg (Canon) on Nov 12, 2003 at 03:53 UTC | |
Re: lvalue substring oddities
by shotgunefx (Parson) on Nov 12, 2003 at 08:38 UTC |