How To trim a string in perl

Articles may may have files attached at the end of the post

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.

  1. #!/usr/bin/env perl
  2. #
  3. use strict;
  4. use warnings;
  5.  
  6. sub trim{
  7.   my $string = $_;
  8.   $string =~ s/^\s*(.*)\s*$/$1/;
  9.   return $string;
  10. }
  11.  
  12. sub ltrim{
  13.   my $string = $_;
  14.   $string =~ s/^\s*//;
  15.   return $string;
  16. }
  17.  
  18. sub rtrim{
  19.   my $string = $_;
  20.   $string =~ s/\s*$//;
  21.   return $string;
  22. }
  23.  
  24.  
  25. my @strings = ("\n\thello\n\r", "hello2\n", "\thello3 spacebar","hello no space");
  26.  
  27. print "## TRIM ##\n";
  28. foreach (@strings){
  29.   print "**".trim($_)."**\n";
  30. }
  31.  
  32. print "## LTRIM ##\n";
  33. foreach (@strings){
  34.   print "**".ltrim($_)."**\n";
  35. }
  36.  
  37. print "## RTRIM ##\n";
  38. foreach (@strings){
  39.   print "**".rtrim($_)."**\n";
  40. }

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**
AttachmentSize
trim.pl.txt595 bytes