- Perl 6 Deep Dive
- Andrew Shitov
- 453字
- 2021-07-03 00:05:41
Signatures
In Perl 5, you had to extract the values of the arguments of a function yourself by using either the built-in shift function, or from the default @_ array.
Let's see this in the following example, with a function to calculate the sum of its two arguments. In Perl 5, you had to do some additional work to get the actual passed parameters.
First, get the argument values with shift in Perl 5:
sub add {
my $x = shift;
my $y = shift;
return $x + $y;
}
Then, by using the @_ array:
sub add {
my ($x, $y) = @_;
return $x + $y;
}
Unlike many other programming languages, it was not possible to declare a list of the function's formal parameters directly. For instance, this is how you do it in C or C++:
int add(int x, int y) {
return x + y;
}
In Perl 5, it is possible to restrict the number of arguments and their structural types with the help of prototypes. Sigils are used there to tell Perl the type of the argument. The preceding function for addition may look like this in Perl 5:
sub add($$) { my ($x, $y) = @_; return $x + $y; }
Using function prototypes will make the compiler complain when the function is used with the different number of arguments (say, one or three instead of two), but you still have to get their values yourself.
Perl 5.20 introduced function signatures. So, now, you may benefit from declaring the arguments in one go. The following code gives an example of such approach. Both $x and $y arguments are declared in the function header.
use v5.20; use feature qw(signatures); no warnings qw(experimental::signatures); sub add($x, $y) { return $x + $y; } say add(4,5);
You will notice that you need to instruct Perl to use the features of Perl 5.20 by mentioning the minimal version number in the script. You will also notice that you must activate the corresponding feature by a separate instruction. However, even more, because signatures are an experimental feature, you have to manually disable the warning message to get a clean output.
In Perl 6, function signatures are allowed from the very beginning, so you may directly use it:
# This is Perl 6 sub add($x, $y) { return $x + $y; }
Actually, signatures in Perl 5.20 are an example of backporting features from Perl 6 to Perl 5. So, despite the fact that Perl 6 was meant to be the next version of Perl 5, Perl 5 still gets some elements that were designed in Perl 6 to make Perl better.
- Photoshop智能手機APP UI設計之道
- JavaScript語言精髓與編程實踐(第3版)
- Raspberry Pi for Secret Agents(Third Edition)
- Hands-On JavaScript High Performance
- 自然語言處理Python進階
- JavaScript入門經典
- Android程序設計基礎
- Web Development with MongoDB and Node(Third Edition)
- Canvas Cookbook
- ASP.NET 4.0 Web程序設計
- INSTANT Apache Hive Essentials How-to
- ANSYS FLUENT 16.0超級學習手冊
- Android從入門到精通
- Internet of Things with Arduino Cookbook
- 秒懂算法:用常識解讀數據結構與算法