A trim() function should be native to perl, but since it isn’t, this will have to do.

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

Notice that I wrote the code to process either a scalar or an array. If the variable that you’re storing the return value from the function is a scalar, then it returns a scalar. If the variable that you’re storing the return value is an array, then it will return an array. This provides a kind of pseudo-polymorphism and makes the function more flexible.

When you call the function, you can pass either a scalar or an array, although in perl, it will send the values as an array anyway. That’s why I’m processing ‘@_‘. You don’t need to worry about this in order to use the function, but if you want to get good at perl, then you should understand what’s going on.

Click here to see all my posts on perl.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.