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

*=

乘法与赋值运算符,将右操作数与左操作数相乘,并将结果赋给左操作数

示例- $c *= $a 相当于 $c = $c * $a

5

/=

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

示例- $c /= $a 相当于 $c = $c / $a

6

%=

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

示例- $c %= $a 相当于 $c = $c % a

7

**=

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

示例- $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_operators.htm