Perl, Trim White Space from a String

When we grep a bunch of string, there are white spaces where we wish to trim, especially the white space at the beginning and the end of a string. There is no trim function in Perl like trim in PHP. The Perl function below should help you to trim the string.


#!/usr/bin/perl

sub trim($);
sub ltrim($);
sub rtrim($);

sub trim($)
{
	my $trim_string = shift;
	$trim_string =~ s/^s+//;
	$trim_string =~ s/s+$//;
	return $trim_string;
}

sub ltrim($)
{
	my $trim_string = shift;
	$trim_string =~ s/^s+//;
	return $trim_string;
}

sub rtrim($)
{
	my $trim_string = shift;
	$trim_string =~ s/s+$//;
	return $trim_string;
}

my $long_string = "  t  foo foo        bar t t bar          ";
print trim($long_string);

Related posts:

  1. Open file and Splitting String in Perl What I gonna do is to read a bunch of...
  2. How to Set VI or VIM Tab Space By default, vi or vim editor tab space is 8...
  3. FreeBSD Port: Error Upgrading Perl 5.8.9 Usually I perform portupgrade daily on some of my FreeBSD...
  4. How to Enable Suidperl in FreeBSD Enable Suidperl In FreeBSD Due to security issues, by default...

Tags: , , ,

2 Responses to “Perl, Trim White Space from a String”

  1. Caleb Cushing ( xenoterracide ) Says:

    Might want to use String::Strip it’s faster. See this previous IronMan post http://www.illusori.co.uk/perl/2010/03/05/advanced_benchmark_analysis_1.html

  2. takizo Says:

    Thanks, will look into that :D

Leave a Reply