结论 $var//=2:等价于 defined($var)||2,即 未定义 时才赋值为 2 ,否则不变( 即使是 0或 空字符串 ) $var||=2 :除非定义且为 true 才不会赋

结论

  • $var//=2:等价于 defined($var)||2,即 未定义 时才赋值为 2 ,否则不变( 即使是 0空字符串
  • $var||=2 :除非定义且为 true 才不会赋值,否则赋值(比如 0空字符串 时)为2。

//=

Step-1 空串

1
2
3
$var='';
$var//=2;
print "'$var'\n";
1
2
# perl atest4.pl 
''

Step-2 0

1
2
3
$var=0;
$var//=2;
print "'$var'\n";
1
2
# perl atest4.pl 
'0'

Step-3 1

1
2
3
$var=1;
$var//=2;
print "'$var'\n";
1
2
# perl atest4.pl 
'1'

Step-4 undef

1
2
3
$var=undef;
$var//=2;
print "'$var'\n";
1
2
# perl atest4.pl 
'2'

||=

Step-1 空串

1
2
3
$var='';
$var||=2;
print $var;
1
2
# perl atest4.pl 
2

Step-2 0

1
2
3
$var=0;
$var||=2;
print $var;
1
2
# perl atest4.pl 
2

Step-3 1

1
2
3
$var=1;
$var||=2;
print $var;
1
2
# perl atest4.pl 
1

Step-4 undef

1
2
3
$var=undef;
$var||=2;
print $var;
1
2
# perl atest4.pl 
2