Perlfunc: trim()

Perl function to trim leading and trailing whitespace.

sub trim {
    my $s = shift();
    if (length($s) == 0) { return ""; }
    $s =~ s/^\s*|\s*$//g;

    return $s;
}

Here is a version that with work with strings and arrays.

sub trim {
    if (wantarray) {
        my @ret;
        foreach (@_) {
            push(@ret,scalar(trim($_)));
        }

        return @ret;
    } else {
        my $s = shift();
        if (!defined($s) || length($s) == 0) { return ""; }
        $s =~ s/^\s*//;
        $s =~ s/\s*$//;

        return $s;
    }
}
Leave A Reply
All content licensed under the Creative Commons License