MENU

Perl //= 和 ||= 的区别 | 附实验

January 12, 2022 • Read: 302 • 编程开发

本文首发于: https://blog.frytea.com

结论

  • $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
Archives QR Code Tip
QR Code for this page
Tipping QR Code
Leave a Comment