views:

220

answers:

2

I have the following test code

use Data::Dumper;

my $hash = {
            foo => 'bar',
            os  => 'linux'
           };

my @keys = qw (foo os);

my $extra = 'test';

my @final_array = (map {$hash->{$_}} @keys,$extra);

print Dumper \@final_array;

The output is

$VAR1 = [
          'bar',
          'linux',
          undef
        ];

Shouldn't the elements be "bar, linux, test"? Why is the last element undefined and how do I insert an element into @final_array? I know I can use the push function but is there a way to insert it on the same line as using the map command?

Basically the manipulated array is meant to be used in an SQL command in the actual script and I want to avoid using extra variables before that and instead do something like:

$sql->execute(map {$hash->{$_}} @keys,$extra);
+6  A: 

$extra is being passed through the map and since there's no entry in the hash with the key test the value is undef. Put parentheses around the map to force the parsing:

$sql->execute((map {$hash->{$_}} @keys),$extra);
Michael Carman
+6  A: 

You can also use a hash slice to avoid looping with map:

my @final_array = (@$hash{@keys}, $extra);
hhunter