This week I will show a simple example about how to use the underscore prototype which is new in Perl 5.10.
This feature was added to allow you to write functions that work like builtin functions. It’s up to you to not abuse it and write unreadable code, of course.
This example shows how to use this new feature. It allows you to use the $_
variable as an argument for a user defined function.
use strict;
use feature 'say';
sub greeting(_) {
my ($greeting) = @_;
$greeting //= 'world';
say "Hello $greeting";
return;
}
for (qw/planet people/) {
greeting();
}
greeting();
The output of the program is:
Hello planet
Hello people
Hello world
As you can see, you don’t need to specify an argument to the greeting
function. The first two calls in the for
loop use the two values from the
loop.
The call outside the loop uses the default value (‘world’) that was specified in the function.