Passing Perl Map Arguments

I am trying to map () with my own routine. When I tried it with the built-in Perl function, it works. But when I tried map () with my own routine, it fails. I could not indicate what makes a mistake.

Here is a snippet of code.

   #!/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";
+4
source share
2 answers

The map always assigns an element to the argument list $_, and then evaluates the expression. Thus, it map mysqr($_), 1,2,3,4,5causes mysqr1,2,3,4,5 for each of the elements, because it is $_set in each of 1,2,3,4,5 in turn.

, $_ , , Perl, , $_ . , lc . mysqr , , , :

    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
+6

, , - .

@answers = map(mysqr, @questions);      # same as mysqr(), no argument passed
@answers = map {mysqr($_)} @questions;  # $_ is passed on to $input

, , Perl $_, . , , . , . , .

, use warnings, , :

Use of uninitialized value $input in multiplication (*) at foo.pl line 8.

, $input.

, , , , .

+2

Source: https://habr.com/ru/post/1532981/


All Articles