Trim Blanks - Perl

 

To remove leading or trailing whitespace use the following pattern substitutions:

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

Here is a function that accomplishes the same thing:

$string = trim($string);
@many   = trim(@many);

sub trim 
{
    my @out = @_;
    for (@out) 
    {
        s/^\s+//;
        s/\s+$//;
    }
    return wantarray ? @out : $out[0];
}

To remove the last character from a string, use the chop function. Use the chomp function to remove the last character if and only if it is contained in the $/ variable, "\n" by default.

# print what's typed, but surrounded by >< symbols
while(<STDIN>) {
    chomp;
    print ">$_<\n";
}