Trim Function in Perl

Perl has no built-in “trim” function so you have to write your own using search and replace and regular expression matching. Below is simple trim function that will remove spaces from the beginning and end of any string you send it and then will return that trimmed string.

Code:
sub trim {
$_[0] =~ s/^\s+//g;
$_[0] =~ s/\s+$//g;
return $_[0];
}#end sub

You can either include this in every program you need it in or you could create a Perl module and then include it with a “use” statement. Of course if you put it into a module you might want to create other kinds of custom trim functions (such as “ltrim” or “rtrim”) and put those in the same module. That’s entirely up to you. Hopefully this little bit of code will at least get you started.


Leave a Reply