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:
Copy Code code as follows:
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:
Copy Code code as follows:
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:
Copy Code code as follows:
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:
Copy Code code 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:
Copy Code code as follows:
My $z = "abc";
printf "<%s>\n", Trim ($z); # <abc>
printf "<%s>\n", LTrim ($z); # <ABC >
printf "<%s>\n", RTrim ($z); # < Abc>
String::util
String::util
If you really don't want to copy those things, you can install a module.
For example, String::util provides a function trim, which you can use as follows:
Copy Code code as follows:
Use String::util QW (trim);
My $z = "abc";
printf "<%s>\n", Trim ($z); # <abc>
printf "<%s>\n", Trim ($z, right => 0); # <ABC >
printf "<%s>\n", Trim ($z, left => 0); # < Abc>
By default it collates both sides and you don't need to provide parameters. I think it will be clearer to realize LTrim and rtrim yourself.
Text::trim
Another module, Text::trim, provides 3 functions, but it is extremely well adapted to the Perl style and may be a bit dangerous.
If you call it and use the return value in the Print statement or assign to a variable, it returns the sorted string and keeps the original string unchanged.
Copy Code code as follows:
Use Text::trim QW (Trim);
My $z = "abc";
printf "<%s>\n", Trim ($z); # <abc>
printf "<%s>\n", $z; # < ABC >
On the other hand, if you call it in a blank context, that is, not using the return value, the TRIM function modifies the parameter to produce a similar chomp behavior.
Copy Code code as follows:
Use Text::trim QW (Trim);
My $z = "abc";
Trim $z;
printf "<%s>\n", $z; # <abc>