Perl removes leading and trailing blanks

Source: Internet
Author: User
Tags regular expression rtrim trim

This article mainly introduces Perl delete leading and trailing blanks (remove left and right spaces, white space characters), this article gives a number of methods to achieve this requirement, the need for friends can refer to the following

In other programming languages, Functions LTrim and RTrim are used to remove spaces and tabs from the beginning and end of a string, respectively. Some also provide the function trim to remove whitespace characters at both ends of the string. Perl does not have these functions because simple regular expression substitutions can do this (although I'm sure Cpan has a lot of modules to implement these functions). In fact it was so simple that it became a prominent subject in the Parkinson's trivial theorem.

Left finishing

LTrim or Lstrip remove white-space characters from the left side of the string:

The code is as follows:

$str =~ s/^s+//;

Start with a string to match one or more white-space characters (s+) and replace them with empty characters.

Right Finishing

RTrim or Rstrip remove white-space characters from the right of the string:

The code is as follows:

$str =~ s/s+$//;

Matches one or more white-space characters (s+) until the end of the string ($) and replaces it with a null character.

Finishing both ends

Trim deletes whitespace characters at both ends of the string:

The code is as follows:

$str =~ s/^s+|s+$//g

The above two regular expressions are connected with or marked |, and the last increment is/g to perform the substitution operation globally (repeatedly).

Encapsulated in function

If you don't want to see these structures in your code, you can add them in your 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};

When used like this:

The code is as follows:

My $z = "abc";

printf "<%S>

Related Article

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.