Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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.

like image 819
Raj Avatar asked Jul 07 '10 07:07

Raj


People also ask

Which function is used to remove leading and trailing whitespaces?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do you trim whitespace from all elements in an array?

Method 3: Basic method using for loop: Use for loop to traverse each element of array and then use trim() function to remove all white space from array elements.

Which function is used for removing whitespaces from beginning?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.

Does trim remove leading and trailing spaces?

TRIM function - remove extra spaces in Excel You use the TRIM function in Excel removes extra spaces from text. It deletes all leading, trailing and in-between spaces except for a single space character between words.


1 Answers

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.

like image 117
Zaid Avatar answered Oct 13 '22 11:10

Zaid