Perl deletes leading and trailing Spaces

Source: Internet
Author: User

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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.