Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl map passing arguments

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";
like image 531
microbe Avatar asked Feb 14 '23 10:02

microbe


1 Answers

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
like image 189
Mark Dominus Avatar answered Mar 30 '23 05:03

Mark Dominus