Skip to content

Instantly share code, notes, and snippets.

@kubrick06010
Created November 6, 2012 04:27
Show Gist options
  • Select an option

  • Save kubrick06010/4022545 to your computer and use it in GitHub Desktop.

Select an option

Save kubrick06010/4022545 to your computer and use it in GitHub Desktop.
Use the subroutine below to trim whitespace (spaces and tabs)
#!/usr/bin/perl
# Taken from http://www.somacon.com/p114.php
# 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment