Showing entries with tag "trim".

Found 2 entries

Perlfunc: trim()

Perl function to trim leading and trailing whitespace.

sub trim {
    my $s = shift();
    if (!defined($s) || length($s) == 0) { return ""; }

    $s =~ s/^\s*//;
    $s =~ s/\s*$//;

    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

Command line trim()

Often I'll need to trim (remove leading and trailing whitespace) from command line output. The easiest way I've found is to pipe to a one line Perl script

my_messy_command.sh | perl -pE 's/^\s+|\s+$//'

This runs a replace regexp on the input, trims extraneous whitespace and outputs the cleaner version.

Leave A Reply