I'm trying map() with my own subroutine. When I tried it with a Perl's builtin function, it works. But when I tried map() with my own subroutine, it fails. I couldn't point out what makes the error.
Here is the code snippet.
#!/usr/bin/perl
use strict;
sub mysqr {
my ($input) = @_;
my $answer = $input * $input;
return $answer;
}
my @questions = (1,2,3,4,5);
my @answers;
@answers = map(mysqr, @questions); # doesn't work.
@answers = map {mysqr($_)} @questions; #works.
print "map = ";
print join(", ", @answers);
print "\n";
Map always assigns an element of the argument list to $_
, then evaluates the expression. So map mysqr($_), 1,2,3,4,5
calls mysqr
on each of the elements 1,2,3,4,5, because $_
is set to each of 1,2,3,4,5 in turn.
The reason you can often omit the $_
when calling a built-in function is that many Perl built-in functions, if not given an argument, will operate on $_
by default. For example, the lc
function does this. Your mysqr
function doesn't do this, but if you changed it to do this, the first form would work:
sub mysqr {
my $input;
if (@_) { ($input) = @_ }
else { $input = $_ } # No argument was given, so default to $_
my $answer = $input * $input;
return $answer;
}
map(mysqr, 1,2,3,4,5); # works now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With