How To trim a string in perl
Articles may may have files attached at the end of the post
Submitted by chantra on Wed, 05/14/2008 - 16:17
trimming a string from whitespaces does not come out of the box in perl. Like for many other operations, we need to use regexes.
This tutorial will show how to trim, ltrim and rtrim a string in Perl.
- #!/usr/bin/env perl
- #
- use strict;
- use warnings;
- sub trim{
- my $string = $_;
- return $string;
- }
- sub ltrim{
- my $string = $_;
- return $string;
- }
- sub rtrim{
- my $string = $_;
- return $string;
- }
- my @strings = ("\n\thello\n\r", "hello2\n", "\thello3 spacebar","hello no space");
- print "## TRIM ##\n";
- foreach (@strings){
- }
- print "## LTRIM ##\n";
- foreach (@strings){
- }
- print "## RTRIM ##\n";
- foreach (@strings){
- }
Will print out:
$ ./trim.pl ## TRIM ## **hello** **hello2** **hello3 spacebar** **hello no space** ## LTRIM ## **hello ** **hello2 ** **hello3 spacebar** **hello no space** ## RTRIM ## ** hello** **hello2** ** hello3 spacebar** **hello no space**
| Attachment | Size |
|---|---|
| trim.pl.txt | 595 bytes |












