Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: function to trim string leading and trailing whitespace

Tags:

perl

Is there a built-in function to trim leading and trailing whitespace such that trim(" hello world ") eq "hello world"?

like image 813
Landon Kuhn Avatar asked Jan 04 '11 20:01

Landon Kuhn


People also ask

How do you remove leading and trailing spaces in Perl?

Removing unwanted spaces from a string can be used to store only the required data and to remove the unnecessary trailing spaces. This can be done using the trim function in Perl. The trim function uses a regular expression to remove white spaces.

How do you cut leading and trailing spaces from a string?

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.

Which function is used to remove leading and trailing whitespace of a string?

strip(): returns a new string after removing any leading and trailing whitespaces including tabs (\t). rstrip(): returns a new string with trailing whitespace removed.

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

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace 

Perl 6 will include a trim function:

$string .= trim; 

Source: Wikipedia

like image 119
Mark Byers Avatar answered Sep 28 '22 08:09

Mark Byers