Advertisement
Advertisement


Why doesn't my Perl map return anything?


Question

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?

2013/08/03
1
5
8/3/2013 5:44:21 PM

Accepted Answer

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.

2008/08/15
10
8/15/2008 9:49:17 AM


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;
2010/01/03

To follow up on Tithonium's point, this will also do the trick:

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

The "local" ensures you're working on a copy, not the original.

2008/09/15

In perl 5.14 you could use the /r regex modifier to make non-destructive substitution.

@filtered = map {s/ //gr} @outdata;
2012/05/18

use Algorithm::Loops "Filter";
@filtered = Filter { s/ //g } @outdata;
2008/12/01

As a counterpoint to Greg's answer, you could misuse grep:

@filtered = grep {s/ //g; 1} @outdata;

Don't do this.

2008/08/17

Source: https://stackoverflow.com/questions/12103
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]