Perl 赋值运算符示例

假设变量 $a 持有 10,变量 $b 持有 20,那么下面是 Perl 中可用的赋值运算符及其用法 −

序号 运算符 & 描述
1

=

简单赋值运算符,将右侧操作数的值分配给左侧操作数

示例 − $c = $a + $b 将 $a + $b 的值赋给 $c

2

+=

加 AND 赋值运算符,它将右操作数添加到左操作数并将结果分配给左操作数

示例 − $c += $a 等价于 $c = $c + $a

3

-=

减 AND 赋值运算符,它从左操作数中减去右操作数并将结果分配给左操作数

示例 − $c -= $a 等价于 $c = $c - $a

4

*=

乘 AND 赋值运算符,它将右操作数与左操作数相乘并将结果分配给左操作数

示例 − $c *= $a 等价于 $c = $c * $a

5

/=

除法 AND 赋值运算符,它将左操作数与右操作数相除并将结果分配给左操作数

示例 − $c /= $a 等价于 $c = $c / $a

6

%=

模 AND 赋值运算符,它使用两个操作数取模并将结果分配给左操作数

示例 − $c %= $a 等价于 $c = $c % a

7

**=

指数与赋值运算符,对运算符执行指数(幂)计算并将值赋给左操作数

示例 − $c **= $a 等价于 $c = $c ** $a


示例

试试下面的例子来理解 Perl 中所有可用的赋值运算符。 将以下 Perl 程序复制并粘贴到 test.pl 文件中并执行该程序。

#!/usr/local/bin/perl
 
$a = 10;
$b = 20;

print "Value of \$a = $a and value of \$b = $b\n";

$c = $a + $b;
print "After assignment value of \$c = $c\n";

$c += $a;
print "Value of \$c = $c after statement \$c += \$a\n";

$c -= $a;
print "Value of \$c = $c after statement \$c -= \$a\n";

$c *= $a;
print "Value of \$c = $c after statement \$c *= \$a\n";

$c /= $a;
print "Value of \$c = $c after statement \$c /= \$a\n";

$c %= $a;
print "Value of \$c = $c after statement \$c %= \$a\n";

$c = 2;
$a = 4;
print "Value of \$a = $a and value of \$c = $c\n";
$c **= $a;
print "Value of \$c = $c after statement \$c **= \$a\n";

当上面的代码被执行时,它会产生下面的结果 −

Value of $a = 10 and value of $b = 20
After assignment value of $c = 30
Value of $c = 40 after statement $c += $a
Value of $c = 30 after statement $c -= $a
Value of $c = 300 after statement $c *= $a
Value of $c = 30 after statement $c /= $a
Value of $c = 0 after statement $c %= $a
Value of $a = 4 and value of $c = 2
Value of $c = 16 after statement $c **= $a

❮ Perl 运算符