- 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.
- Mastering NetBeans
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- Python數據分析入門與實戰
- 潮流:UI設計必修課
- Vue.js快跑:構建觸手可及的高性能Web應用
- Flux Architecture
- Python深度學習原理、算法與案例
- 分布式架構原理與實踐
- Java 9 with JShell
- Visual C++程序設計與項目實踐
- Java RESTful Web Service實戰
- SQL Server on Linux
- Python滲透測試編程技術:方法與實踐(第2版)
- Internet of Things with Arduino Cookbook
- VMware vRealize Orchestrator Essentials