Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, unknown result of the `map` function

Tags:

arrays

perl

I get a very strange result in print @squares array below; I should have got 49 but I get some random number:

@numbers={-1,7};

my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;

print @squares;

$ perl g.pl

12909907697296

like image 392
user2925716 Avatar asked May 16 '21 16:05

user2925716


1 Answers

This is incorrect:

@numbers={-1,7};

{ } builds a hash and returns a reference to the hash. The above is equivalent to

my %anon = ( -1 => 7 );
@numbers = \%anon;

A reference treated as a number returns the underlying pointer as a number, so you get garbage.


To populate an array, use

my @numbers = ( -1, 7 );

-1, 7 returns two numbers, which are added to the array when assigned to the array. (The parens aren't special; they just override precedence like in math.)


The complete program:

use 5.014;      # ALWAYS use `use strict;` or equivalent! This also provides `say`.
use warnings;   # ALWAYS use `use warnings;`!

my @numbers = ( -1, 7 );

my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;

# Print each number on a separate line.
# Also provides the customary final line feed.
say for @squares;

Alternative:

my @squares =
   map { $_ * $_ }
      grep { $_ > 5 }
         @numbers;
like image 185
ikegami Avatar answered Oct 13 '22 10:10

ikegami