Posted By

alwaysonnet on 06/15/11


Tagged

trim leading trailing spaces


Versions (?)

strip leading and trailing spaces


 / Published in: Perl
 

  1. #!/usr/bin/perl
  2.  
  3. # subroutine to strip leading and trailing spaces
  4. # in a string or an array.
  5.  
  6. # check for the examples below.
  7.  
  8. ################################################################################
  9. # trim()
  10. #
  11. # Usage:
  12. # trim; # trims $_ inplace
  13. # $new = trim; # trims (and returns) a copy of $_
  14. # trim($str); # trims $str inplace
  15. # $new = trim($str); # trims (and returns) a copy of $str
  16. # trim(@list); # trims @list inplace
  17. # @new = trim(@list); # trims (and returns) a copy of @list
  18. #################################################################################
  19. sub trim {
  20. @_ = $_ if not @_ and defined wantarray;
  21. @_ = @_ if defined wantarray;
  22.  
  23. for (@_ ? @_ : $_) { s/^\s+//, s/\s+$// }
  24.  
  25. return wantarray ? @_ : $_[0] if defined wantarray;
  26. }

Report this snippet  

You need to login to post a comment.