Perl deletes leading and trailing Spaces
This article mainly introduces Perl to delete leading and trailing spaces (remove left and right spaces and blank characters). This article provides multiple methods to solve this problem. For more information, see
In other programming languages, the ltrim and rtrim functions are used to delete spaces and tabs from the beginning and end of a string. Some also provide the function trim to delete the white spaces at both ends of the string. Perl does not have these functions because simple regular expressions can be replaced (but I'm sure many modules of CPAN implement these functions ). In fact, this is so simple that it has become a prominent topic in Parkinson's trivial theorem.
Organize on the left
Ltrim or lstrip removes white spaces from the left side of the string:
The Code is as follows:
$ Str = ~ S/^ \ s + //;
Matches one or more blank characters (\ s +) starting with the character string ^ and replaces it with null characters.
Right-side sorting
Rtrim or rstrip removes white spaces from the right side of the string:
The Code is as follows:
$ Str = ~ S/\ s + $ //;
Match one or more white space characters (\ s +) until the end of the string ($), and replace it with a null character.
Sort ends
Trim Deletes white spaces at both ends of a string:
The Code is as follows:
$ Str = ~ S/^ \ s + | \ s + $/g
Connect the above two regular expressions with or mark |, and add/g at the end to perform the replacement operation globally (multiple times ).
Encapsulated in Functions
If you do not want to see these structures in the code, you can add these functions in the Code:
The Code is as follows:
Sub ltrim {my $ s = shift; $ s = ~ S/^ \ s + //; return $ s };
Sub rtrim {my $ s = shift; $ s = ~ S/\ s + $ //; return $ s };
Sub trim {my $ s = shift; $ s = ~ S/^ \ s + | \ s + $ // g; return $ s };
The usage is as follows:
The Code is as follows:
My $ z = "abc ";
Printf "<% S>