When I trim a string, I don't often want to keep the original. It would be nice to have the abstraction of a sub but also not have to fuss with temporary values.
It turns out that we can do just this, as perlsub explains:
Any arguments passed in show up in the array @_. Therefore, if you called a function with two arguments, those would be stored in $_[0] and $_[1]. The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable).
In your case, trim becomes
sub trim {
for (@_) {
s/^ \s+ //x;
s/ \s+ $//x;
}
wantarray ? @_ : $_[0];
}
Remember that map and for are cousins, so with the loop in trim, you no longer need map. For example
my $line = "1\t 2\t3 \t 4 \t 5 \n";
my ($a, $b, $c, $d, $e) = split(/\t/, $line);
print "BEFORE: [", join("] [" => $a, $b, $c, $d), "]\n";
trim $a, $b, $c, $d;
print "AFTER: [", join("] [" => $a, $b, $c, $d), "]\n";
Output:
BEFORE: [1] [ 2] [3 ] [ 4 ]
AFTER: [1] [2] [3] [4]