- 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.
- Learning Java Functional Programming
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- 碼上行動:零基礎學會Python編程(ChatGPT版)
- Learning Laravel's Eloquent
- Python之光:Python編程入門與實戰
- Android移動應用開發項目教程
- 超好玩的Scratch 3.5少兒編程
- Mastering SciPy
- Web前端開發技術:HTML、CSS、JavaScript
- Building Microservices with Go
- C語言編程魔法書:基于C11標準
- Python深度學習與項目實戰
- HTML5 and CSS3:Building Responsive Websites
- iOS應用逆向工程:分析與實戰
- 區塊鏈原理、架構與應用(第2版)