Thursday, October 01, 2009

Trim whitespace from string in PERL

I like Java's String.trim() method, and so I thought I would add one for PERL:

sub trim {
my ($self, $text) = @_;
$text = $self
if ref(\$self) =~ m/^SCALAR/i;
# return empty string if $text is not defined
return "" unless $text;
$text =~ s/^\s+//;
$text =~ s/\s+$//;
return $text;
}

That is all that there is to it!

You can add this to your module, and do $self->trim($string) or you can do trim($string) ... If you have anything to add, let me know!