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

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.

主站蜘蛛池模板: 巨鹿县| 新民市| 兰州市| 遂宁市| 芒康县| 和田市| 天长市| 射阳县| 将乐县| 察隅县| 樟树市| 晋州市| 精河县| 泾阳县| 英吉沙县| 大方县| 新丰县| 开封市| 罗甸县| 孟州市| 环江| 开远市| 浦江县| 兴义市| 四川省| 鄂伦春自治旗| 庆安县| 宁乡县| 府谷县| 邢台县| 团风县| 库尔勒市| 静宁县| 马龙县| 清新县| 富源县| 揭阳市| 乐陵市| 翁源县| 拜城县| 囊谦县|