Marius van Witzenburg "Learned my lesson in life, now setting my action to stay in life."

3Aug/102

How to: trim whitespace with some custom subroutine in Perl

Since perl does not have a built-in trim function (yet). Use the subroutine below to trim whitespace (spaces and tabs) from the beginning and end of a string in Perl. This function is directly based on the Perl FAQ entry, How do I strip blank space from the beginning/end of a string?. The ltrim and rtrim functions can trim leading or trailing whitespace.

#!/usr/bin/perl
 
# Declare the subroutines
sub trim($);
sub ltrim($);
sub rtrim($);
 
# Create a test string
my $string = "  \t  Hello world!   ";
 
# Here is how to output the trimmed text "Hello world!"
print trim($string)."\n";
print ltrim($string)."\n";
print rtrim($string)."\n";
 
# Perl trim function to remove whitespace from the start and end of the string
sub trim($) {
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}
# Left trim function to remove leading whitespace
sub ltrim($) {
	my $string = shift;
	$string =~ s/^\s+//;
	return $string;
}
# Right trim function to remove trailing whitespace
sub rtrim($) {
	my $string = shift;
	$string =~ s/\s+$//;
	return $string;
}
4Jul/100

The triminator attacking the hedge with a trimming machine >:-)

After about 8 months of having not time to trim the hedge to day it was finally the day to start the battle.

The hedge before the battle
IMG 0002 384x512 The triminator attacking the hedge with a trimming machine >: )

The triminator who is going for the battle
IMG 0003 384x512 The triminator attacking the hedge with a trimming machine >: )

The hedge after the battle
IMG 0004 384x512 The triminator attacking the hedge with a trimming machine >: )

The triminator won the battle
IMG 0006 384x512 The triminator attacking the hedge with a trimming machine >: )