Question

why does map function changes the value of the input array in perl? To illustrate,

#!/usr/bin/env perl


use strict;
use warnings;
use v5.10;


my @words = <DATA>;

# want to have another array that contains the each word in reverse order
my @reverse_words =  map {  $_   =  scalar reverse $_    } @words;

say $words[0]; # want to check the content of first element of original array
say $reverse_words[0]; # new 



__DATA__
aarhus
aaron
ababa
aback

But this prints

 $perl findPalindrome.pl

suhraa

suhraa

Why is the original array altered?

Was it helpful?

Solution

Because you asked it to by modifying $_.

You want

my @reverse_words = map { scalar reverse $_ } @words;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top