Raj
Raj

Reputation: 767

How can I remove leading and trailing whitespaces from array elements?

I have an 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.

Upvotes: 9

Views: 33441

Answers (6)

Eric Van Bezooijen
Eric Van Bezooijen

Reputation: 619

The highest rated answer here looked fine but is, IMHO, not as easy to read as it could be. I added a string with internal spaces to show those are not removed.

#!/usr/bin/perl

use strict;
use warnings;

my @array = ("shayam    "," Ram        "," 24.0       ", " foo bar garply  ");

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

for my $element (@array) {
    print ">$element<\n";
}

The output:

>shayam<
>Ram<
>24.0<
>foo bar garply<

Upvotes: 3

lkench
lkench

Reputation: 11

How about: @array = map {join(' ', split(' '))} @array;

Upvotes: 1

Zaid
Zaid

Reputation: 37146

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.

Upvotes: 39

bohica
bohica

Reputation: 5990

I think Borealid's example should be:

my @array = ("shayam "," Ram "," 24.0 ");
foreach my $el (@array) {
   $el =~ s/^\s*(.*?)\s*$/\1/;
}

Upvotes: -1

Alan Horn
Alan Horn

Reputation: 80

#!/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.

Upvotes: 1

Borealid
Borealid

Reputation: 98509

my @res = ();
my $el;

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

After this, @res will contain your desired elements.

Upvotes: -1

Related Questions