strip leading and trailing spaces


/ Published in: Perl
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.