官术网_书友最值得收藏!

  • Perl 6 Deep Dive
  • Andrew Shitov
  • 344字
  • 2021-07-03 00:05:55

Operators as functions

Operators perform some actions over their arguments. Operator's arguments are called operands. In the preceding example, the + operator takes two operands, $a and $b. The = operator also takes two operands—on the left side of it, it expects the variable, to which it will assign the value of the operand on the right side.

In any programming language, operators are simply a handy syntactical solution to have more expressive programs and can be replaced with calling a function. For example, in the preceding example, you write $c = $a + $b, but you can also do the same by calling the add function that we saw in Chapter 1What is Perl 6?. Let's rewrite the previous example:

my $a = 10;
my $b = 20;
my $c = 0;
$c = add($a, $b);
say $c; # 30

sub add($a, $b) {
return $a + $b;
}

Of course, the add function uses the + operator itself, but we cannot avoid it here because there are no more low-level functions for addition in Perl 6. The purpose of the example was to demonstrate that operators can always be treated as functions that accept a few arguments and return a value, but you do not call them directly; rather via a good-looking operator.

In Perl 6, you may use the functional style when working with operators. For that, use the keyword with the name of the category of the operator followed by the colon and the operator itself in angle brackets. Then, pass the arguments as you do with functions. The following example demonstrates this on the example of the + infix operator:

my $a = 10;
my $b = 20;
my $c = infix:<+>($a, $b); # same as $c = $a + $b
say $c; # 40

Now, let's discuss the categories of the operators that Perl 6 offers.

And now, it's time to examine the operators one by one.

主站蜘蛛池模板: 长垣县| 同江市| 从化市| 剑川县| 宜春市| 化隆| 内江市| 阳泉市| 会同县| 乌拉特中旗| 道真| 额敏县| 开化县| 铜川市| 余姚市| 都昌县| 宝兴县| 五寨县| 安庆市| 枣阳市| 察雅县| 裕民县| 江川县| 防城港市| 通渭县| 布尔津县| 大同市| 沈阳市| 营口市| 句容市| 岳普湖县| 镶黄旗| 和硕县| 南木林县| 泸水县| 普宁市| 漠河县| 保定市| 拉孜县| 双流县| 调兵山市|