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. It is not a library function but defined by the user whenever required. The types of trim functions are:
- Left Trim (~ s/^\s+//): Removes extra spaces from leftmost side of the string till the actual text starts. From the leftmost side the string takes 1 or more white spaces (\s+) and replaces it with nothing.
- Right Trim (~ s/\s+$//): Removes extra spaces from rightmost side of the string till the actual text end is reached. From the rightmost side the string takes 1 or more white spaces (\s+) and replaces it with nothing.
- Trim (~ s/^\s+|\s+$//): It removes extra space from both sides of the string.
Example: The following code demonstrates the left trim, right trim and trim in Perl:
# Perl program for removing leading and # trailing white spaces using trim #!/usr/bin/perl # Original String $str1 = " Geeks----"; print"The Original String is:\n"; print"${str1}\n\n"; # Applying left trim to str1 print"After Lefttrim Str1:\n"; $str1=~ s/^\s+//; print"${str1}\n\n"; # again initializing the # value to string $str1 = "----Geeks "; # Applying right trim to str1 print"After Righttrim Str1:\n"; $str1=~ s/\s+$//; print"${str1}\n\n"; # again initializing the # value to strings $str1=" Geeks "; # Applying trim to str1 print"After trim Str1:\n"; $str1=~ s/^\s+|\s+$//g; print"${str1}\n"; |
Output:
The Original String is:
Geeks----
After Lefttrim Str1:
Geeks----
After Righttrim Str1:
----Geeks
After trim Str1:
Geeks
Recommended Posts:
- Perl | Basic Syntax of a Perl Program
- Perl Tutorial - Learn Perl With Examples
- Perl Installation and Environment Setup in Windows, Linux, and MacOS
- Perl | undef and the defined function
- Perl | Variables and its Types
- Perl | Constructors and Destructors
- Perl | Finding Files and Directories
- Perl | Opening and Reading a File
- Perl | STDIN in Scalar and List Context
- Perl List and its Types
- Perl | Quoted, Interpolated and Escaped Strings
- Perl | Number and its Types
- Perl | Mutable and Immutable parameters
- Perl | Hash in Scalar and List Context
- Use of print() and say() in Perl
- Encryption and Decryption In Perl
- Perl | Grouping and Alternation in Regex
- Perl | Date and Time
- Perl | Warnings and how to handle them
- Perl | Greedy and non-greedy match
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Code_Mech

