in reply to Bug with substring return value?

Try:
my $result = substr($string,2,6,''); print $result,"\n"; # Result is 234567
perldoc -f substr:
An alternative to using substr() as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice().

I agree that the assignment way is pretty weird and contraintuitive, but I guess there is a reason... such as the possibility to use both ways depending on what you want to acheive?

Update: I just realized that it makes a bit more sense when you think about this:
$x = $y = 42;
Which sets first $y to 42, then $x to the value of $y. In which case, you set the substring to a value, then that value is propagated to the next variable. And when you assign a substring to an empty string, it shrinks, and then the substring from position 2 to 7 is returned (which is now what was in positions 8 to 13). Heh. Still pretty weird anyways, but there is method to the madness. :)
You have moved into a dark place.
It is pitch black. You are likely to be eaten by a grue.

Replies are listed 'Best First'.
Re: Re: Bug with substring return value?
by shotgunefx (Parson) on Apr 13, 2002 at 12:44 UTC
    This allows you to replace parts of the EXPR and return what was there before in one operation

    But that's not what this is doing. I'm getting the assigned value or I'm missing something deceptively obvious.
    update
    I had my stupid hat on today.


    -Lee

    "To be civilized is to deny one's nature."
      Ok, here is what I think is happening (according to the examples above):
      $y = 42; $x = $y; substr( $string, 2, 6 ) = ''; $result = substr( $string, 2, 6 );
      The other ways of writing it, $x = $y = 42; and your example are just shorthand ways.

      And perldoc specifically mentions the way when you use a fourth argument instead as an alternative where you can get the replaced values back, unlike the assignment way.


      You have moved into a dark place.
      It is pitch black. You are likely to be eaten by a grue.
        DOH!
        Apparently when I code 20 hour straight I lose the basic ability to do simple addition. I'm not quite firing on all cylinders today.

        ++Thanks you for the very polite (considering the stupidity of my reply) dope slap.



        -Lee

        "To be civilized is to deny one's nature."