I am new to Perl and I'm trying to understand the map function.
my %names = qw (hanibal lecter Harry Potter INDIANA JONES Sarah connor scarlet O’Hara JAMES Bond);
my ($k, $v);
my @names;
while (($k,$v) = each %names) {
my @name ;
push(@name , $k);
push(@name , $v);
push(@names, \@name);
}
print "Unsorted names : \n";
foreach(0..$#names) {
print "@{$names[$_]}\n";
}
This works, and prints all the names like this
hanibal lecter
scarlet O¦Hara
Harry Potter
Sarah connor
INDIANA JONES
JAMES Bond
I have modified a little my code and know it looks like this:
my %names = map { $_ } qw (hanibal lecter Harry Potter INDIANA JONES Sarah connor scarlet O’Hara JAMES Bond);
my ($k, $v);
my @names;
while (($k,$v) = each %names) {
my @name = map {$k, $v} ($k,$v) ;
#my @name;
#push(@name , $k);
#push(@name , $v);
push(@names, \@name);
}
foreach(0..$#names) {
print "@{$names[$_]}\n";
}
The hash is created corectly but the array is not The output is
hanibal lecter hanibal lecter
scarlet O▒Hara scarlet O▒Hara
Harry Potter Harry Potter
Sarah connor Sarah connor
INDIANA JONES INDIANA JONES
JAMES Bond JAMES Bond
Why does it double every record?