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

I have an array containing a string that may contain spaces added. I need to remove these spaces using a perl script. my array will look like this

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

I need a conclusion like

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

I tried with chomp (@array) . It does not work with strings.

+7
perl
source share
6 answers
 #! / 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 a demo sauce.

+1
source share

The main question is related to the removal of material and trailing spaces from lines, and in some cases it was answered in several threads with the following replacement of the regular expression (or its equivalent):

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

chomp Only trailing separators of input records will be deleted into the array ( "\n" by default). It is not intended to remove trailing spaces.

From perldoc -f chomp :

It is often used to remove a new line from the end of an input record when you are worried that the last record may not have a new line. When in paragraph mode ( $/ = "" ), it removes all trailing lines of a newline from a line.

...

If you interrupt the list, each item is interrupted and the total number of characters deleted is returned.

+32
source share

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

+1
source share

The highest rated answer here looked great, but it, IMHO, is not as easy to read as it could be. I added a line with internal spaces to show that they 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"; } 

Exit:

 >shayam< >Ram< >24.0< >foo bar garply< 
+1
source share
 my @res = (); my $el; foreach $el (@array) { $el =~ /^\s*(.*?)\s*$/; push @res, $1; } 

After that, @res will contain the necessary elements.

-one
source share

I think the Borealid example should be:

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

All Articles