PERL Trim Functions

PERL is a wonderful scripting language, it is extremely powerful, flexible and portable. It also lacks a couple basic functions that other languages have built in. Fear not my friend, just like the PERL round function, I have functions for other things as well!

One thing I miss is a trim function. They have chop and chomp, but that doesn’t always fit what I want. Below I have included a few suns that will get the job done nicely, check it out.

Here we have a trim sub:

# This sub will remove white spaces from the beginning and end of the string
sub trim($) {
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}

This is a left side only trim sub:

# This sub will remove leading white spaces only (at the beginning)
sub ltrim($) {
	my $string = shift;
	$string =~ s/^\s+//;
	return $string;
}

This is a right side only trim sub:

# This sub will remove trailing white spaces only (at the end)
sub rtrim($) {
	my $string = shift;
	$string =~ s/\s+$//;
	return $string;
}

There you have it, rip out those white spaces whenever you want to. Enjoy.

Tell me what you are thinking?