Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my Perl map return anything?

Tags:

map

perl

When I am running the following statement:

@filtered = map {s/ //g} @outdata;

it is returning an empty list instead of the filtered list that I expected. What I am trying to do is remove every occurrence of   from an array of string (which is an XML file).

Obviously, I am not understanding something. Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?

like image 663
Xetius Avatar asked Aug 15 '08 09:08

Xetius


3 Answers

Note that map is going to modify your source array as well. So you could either do:

map {s/ //g} @outdata;

and skip the @filtered variable altogether, or if you need to retain the originals,

@filtered = @outdata;
map {s/ //g} @filtered;

Although, in that case, it might be more readable to use foreach:

s/ //g foreach @filtered;
like image 128
Tithonium Avatar answered Oct 31 '22 00:10

Tithonium


Try this:

@filtered = map {s/ //g; $_} @outdata;

The problem is the s operator in perl modifies $_ but actually returns the number of changes it made. So, the extra $_ at the end causes perl to return the modified string for each element of @outdata.

like image 10
Greg Hewgill Avatar answered Oct 30 '22 23:10

Greg Hewgill


Greg's answer has the problem that it will modify the original array as the $_ are passed aliased. You need:

@filtered = map { (my $new = $_) =~ s/ //g; $new} @outdata;
like image 9
Shlomi Fish Avatar answered Oct 30 '22 23:10

Shlomi Fish