- 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 1, What 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.
- Implementing Modern DevOps
- Oracle從新手到高手
- 摩登創(chuàng)客:與智能手機和平板電腦共舞
- Learning Flask Framework
- Python網(wǎng)絡(luò)爬蟲從入門到實踐(第2版)
- Visual C++串口通信技術(shù)詳解(第2版)
- Android NDK Beginner’s Guide
- 教孩子學編程:C++入門圖解
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- Python完全自學教程
- 學Python也可以這么有趣
- Unity 5 for Android Essentials
- 學習正則表達式
- HTML5與CSS3基礎(chǔ)教程(第8版)
- Scratch·愛編程的藝術(shù)家