Kunaljain's Weblog

December 7, 2007

Removing spaces in Perl

Filed under: Perl — Kunal Jain @ 06:22

Perl trim function to remove whitespaces from the start and end of the string

sub trim($)

{

mys $string = shift;

$string =~ s/^\s+//;

$string =~ s/\s+$//;

return $string;

}

OR

sub trim($)

{

$string = shift;

$string =~ s/^\s+|\s+$//g;

return $string ;

}

Left trim function to remove leading whitespaces

sub ltrim($)

{

my $string = shift;

$string =~ s/^\ s+//;

return $string;

}

Right trim function to remove trailing whitespaces

sub rtrim($)

{

my $string = shift;

$string =~ s/\s+$//;

return $string;

}

Advertisements

2 Comments »

  1. You can even combine the 2 steps of the trim() sub-routine into one:
    $string =~ s/^\s+|\s+$//g;

    Comment by Lazy Sunday Blogger — December 7, 2007 @ 09:58 | Reply

  2. yup! its working fine. Thanks a lot.

    Comment by Kunal Jain — December 7, 2007 @ 10:36 | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: