If you implement your own substr (swab2 below) then you get yet another behavior---it always returns '\0B'---but you can see the order things are being called in. The substr's are evaluated left-to-right and are always working on the original string---it seems to do all of the substr's first, then do the assignments. In that case, you'd get:
char 0: A ^ B ^ A ^ B = \0 char 1: B ^ A ^ B = Awhich is what you're seeing. On the other hand, if you use assignments to guarantee the order things are evaluated in (swab3 below), you get the results you'd expect.
I think you may simply be running into a case where Perl's order of operations is undefined. It can evaluate xor's, substr's, and assignments in any order it feels like, and it doesn't always feel like doing it the same way.
Here's the code I played with, and the results.
produces:#!/usr/bin/perl -slw sub mysubstr : lvalue { print "mysubstr(@_)"; print "Returning value '",substr($_[0],$_[1],$_[2]),"' as lvalue."; substr($_[0],$_[1],$_[2]); } sub swab{ my $s = "swab$ARGV[0]"; goto &$s; } sub swab1{ substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ) ^= substr( $_[0], $_[1], 1 ) ^= substr( $_[0], $_[2], 1 ); } sub swab2{ mysubstr( $_[0], $_[1], 1, "1" ) ^= mysubstr( $_[0], $_[2], 1, "2" ) ^= mysubstr( $_[0], $_[1], 1, "3" ) ^= mysubstr( $_[0], $_[2], 1, "4" ); } sub swab3{ my($c1,$c2); print " Char $_[2]: ",$c2 = substr($_[0],$_[2],1); print " Char $_[1]: ",$c1 = substr($_[0],$_[1],1); print " 1 ^ 2: ",$c1 = $c1 ^ $c2; print " 2 ^ 1 ^ 2: ",$c2 = $c2 ^ $c1; print "1 ^ 2 ^ 2 ^ 2: ",$c1 = $c1 ^ $c2; substr($_[0],$_[1],1)=$c1; substr($_[0],$_[2],1)=$c2; } my $t; $t ='AB'; swab( $t, 0, 1 ); print "'$t'"; print "'$t'"; print "length: ",length($t); $t ='AB'; swab( $t, 0, 1 ); print "'$t'"; print "'$t'"; print "length: ",length($t);
$ perl /tmp/t55 1
'BA'
'BA'
length: 2
'A'
'A'
length: 2
$ perl /tmp/t55 2
mysubstr(AB 0 1 1)
Returning value 'A' as lvalue.
mysubstr(AB 1 1 2)
Returning value 'B' as lvalue.
mysubstr(AB 0 1 3)
Returning value 'A' as lvalue.
mysubstr(AB 1 1 4)
Returning value 'B' as lvalue.
'B'
'B'
length: 2
mysubstr(AB 0 1 1)
Returning value 'A' as lvalue.
mysubstr(AB 1 1 2)
Returning value 'B' as lvalue.
mysubstr(AB 0 1 3)
Returning value 'A' as lvalue.
mysubstr(AB 1 1 4)
Returning value 'B' as lvalue.
'B'
'B'
length: 2
$ perl /tmp/t55 3
Char 1: B
Char 0: A
1 ^ 2:
2 ^ 1 ^ 2: A
1 ^ 2 ^ 2 ^ 2: B
'BA'
'BA'
length: 2
Char 1: B
Char 0: A
1 ^ 2:
2 ^ 1 ^ 2: A
1 ^ 2 ^ 2 ^ 2: B
'BA'
'BA'
length: 2
In reply to Re: An obscure side effect?
by sgifford
in thread An obscure side effect?
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |