2

Perl map passing arguments

 2 years ago
source link: https://www.codesd.com/item/perl-map-passing-arguments.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Perl map passing arguments

advertisements

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK