结论
$var//=2
:等价于defined($var)||2
,即 未定义 时才赋值为2
,否则不变( 即使是0
或空字符串
)$var||=2
:除非定义且为true
才不会赋值,否则赋值(比如0
或空字符串
时)为2。
//=
Step-1 空串
$var='';
$var//=2;
print "'$var'\n";
# perl atest4.pl
''
Step-2 0
$var=0;
$var//=2;
print "'$var'\n";
# perl atest4.pl
'0'
Step-3 1
$var=1;
$var//=2;
print "'$var'\n";
# perl atest4.pl
'1'
Step-4 undef
$var=undef;
$var//=2;
print "'$var'\n";
# perl atest4.pl
'2'
||=
Step-1 空串
$var='';
$var||=2;
print $var;
# perl atest4.pl
2
Step-2 0
$var=0;
$var||=2;
print $var;
# perl atest4.pl
2
Step-3 1
$var=1;
$var||=2;
print $var;
# perl atest4.pl
1
Step-4 undef
$var=undef;
$var||=2;
print $var;
# perl atest4.pl
2