Perl-assignment-operators-example

提供:Dev Guides
移動先:案内検索

Perl割り当て演算子の例

変数$ aが10を保持し、変数$ bが20を保持すると仮定すると、Perlで使用可能な代入演算子とその使用法は次のとおりです-

Sr.No. Operator & Description
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代入演算子。2つのオペランドを使用してモジュラスを取り、結果を左のオペランドに割り当てます。

-$ c%= $ aは$ c = $ c%aと同等

7

*=*

指数AND代入演算子、演算子で指数(べき乗)計算を実行し、左のオペランドに値を割り当てます

-$ c * = $ aは$ c = $ c *$ aと同等

Perlで使用可能なすべての割り当て演算子を理解するには、次の例を試してください。 test.plファイルに次のPerlプログラムをコピーして貼り付け、このプログラムを実行します。

#!/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