Slightly cleaner:
my @array2 = @array1;
s/\s+//g for (@array2);
Or in a single statement:
my @array2 = map {(my $x = $_) =~ s/\s+//g; $x} @array1;
The main concern you must have when dealing with map and a regex is not destructing the original array unless you truly intend to. $_ is an alias to each element of the source array, so any modification of it modifies the original array. To avoid this we assign to a temporary lexical in the above map block. And then finally make sure to return the actual variable and not a count of the number of substitutions.
Personally, I'd probably just stick with your original code, as I kind of doubt that you truly need a second array with these crunched values. Instead simply add the "crunching" as part of the loop for whatever other processing that you intend to be doing. Whatever that may be.
- Miller
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|