tags:

views:

134

answers:

4

I have a array that contains string which may contain whitespaces appended to the end. I need to remove those spaces using perl script. my array will look like this

@array = ("shayam    "," Ram        "," 24.0       ");

I need the output as

@array = ("shayam","Ram","24.0");

I tried with chomp (@array). It is not working with the strings.

Thanks in advance.

A: 
my @res = ();
my $el;

foreach $el (@array) {
   $el =~ /^\s*(.*?)\s*$/;
   push @res, $1;
}

After this, @res will contain your desired elements.

Borealid
This is unidiomatic Perl.
daxim
@daxim: You mean because you can read it? I thought Perl was all about freedom of choice.
Borealid
Ridiculous. It is just one line with `map` or [`foreach` (as Zaid shows)](http://stackoverflow.com/questions/3192649#3192716), and therefore more readable. `my $el; foreach $el …` is the style of an unversed beginner, everyone else writes `foreach my $el …`. Also, [bicarbonate](http://en.wikipedia.org/wiki/There's_more_than_one_way_to_do_it). Sorry, I don't think your answer is that good and deserves its lack of upvotes.
daxim
It is unidiomatic because you are capturing unnecessarily and creating a new array by individually pushing elements rather than modifying the elements of the original array inplace as the OP's question states. If a new array is going to be created, use `map`, if elements of the array will be modified inplace, use `for`.
Sinan Ünür
A: 
#!/usr/local/bin/perl -w

use strict;
use Data::Dumper;

my @array=('a ', 'b', '  c');

my @newarray = grep(s/\s*$//g, @array);

print Dumper \@newarray;

The key function here is grep(), everything else is just demo gravy.

Alan Horn
Wouldn't `map` be more appropriate?
el.pescado
map is more complex than is needed here. Since you know that the regex will always return true, whilst at the same time modifying $_, grep is the best choice.All these folks that are going on with these silly foreach loops clearly haven't read the first couple of chapters of any basic perl book. grep is bread and butter for perl :)
Alan Horn
(reply to Alan Horn) IMO 'grep' suggests searching for something in a list, 'map' suggests that the whole list will be used, therefore using 'grep' where a 'map' is more appropriate makes the code less immediately readable
plusplus
I cannot help it if you don't know the language.<pre>perldoc -f grepEvaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consist‐ ing of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.</pre>in the world of perl, a grep is an extremely well understood function and is used for this precise thing all the time. Map is not (although it could be).
Alan Horn
i know both grep and map very well, but i am talking about what they *imply* to me at first glance, and consideration of such factors makes code more readable and hence maintainable by others. the definition of grep just confirms this - 'those elements for which the expression evaluated to true' - in this case *all* the elements are returned, so that is unecessary confusion - if i see a grep i start looking for what exactly will be matched by the grep condition, but if i see a map i know that everything will be used from the input list
plusplus
and it obviously depends on personal experience as to which is most common, but i've both seen and used map more than grep in 10+ years of Perl
plusplus
And in 15+ years I've seen grep used a bunch more, so yes, personal choice really :)
Alan Horn
+12  A: 

The underlying question revolves around removing leading and trailing whitespace from strings, and has been answered in several threads in some form or another with the following regex substitution (or its equivalent):

s{^\s+|\s+$}{}g foreach @array;

chomping the array will remove only trailing input record separators ("\n" by default). It is not designed to remove trailing whitespaces.

From perldoc -f chomp:

It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode ($/ = ""), it removes all trailing newlines from the string.

...

If you chomp a list, each element is chomped, and the total number of characters removed is returned.

Zaid
This is the correct answer. The OP is asking for the elements of the array to be modified inplace, rather than creating a new array. Also, the solutions with capturing, while not incorrect, are bound to be slower. See also perlfaq: http://perldoc.perl.org/perlfaq4.html#How-do-I-strip-blank-space-from-the-beginning%2fend-of-a-string%3f
Sinan Ünür
A: 

I think Borealid's example should be:

my @array = ("shayam "," Ram "," 24.0 ");
foreach my $el (@array) {
   $el =~ s/^\s*(.*?)\s*$/\1/;
}
bohica
"it may throw some surprises if there are spaces within each string". What are the surprises then?
bohica
Avoid using `\1` on the RHS of the substitution. Plus, there is no need to capture here. See perlfaq: http://perldoc.perl.org/perlfaq4.html#How-do-I-strip-blank-space-from-the-beginning%2fend-of-a-string%3f and perlre: http://perldoc.perl.org/perlre.html#Warning-on-%5c1-Instead-of-%241
Sinan Ünür