Abort this line by line because it was not:
sub trim { @_ = $_ if not @_ and defined wantarray; # if there are no arguments, but a return value is requested # then place a copy of $_ into @_ to work on @_ = @_ if defined wantarray; # if the caller expects a return value, copy the values in @_ into itself # (this breaks the aliasing to the caller variables) for (@_ ? @_ : $_) { s/^\s+//, s/\s+$// } # perform the substitution, in place, on either @_ or $_ depending on # if arguments were passed to the function return wantarray ? @_ : $_[0] if defined wantarray; # if called in list context, return @_, otherwise $_[0] }
I agree that the code gets a little tedious with all the wantarray checks, but the result is a function that has a level of flexibility with Perl built-in functions. The end result of creating a smart function is to clear the call site (excluding cyclic constructs, temporary variables, repetition, ...), which, depending on the frequency of use of the function, can significantly improve the readability of the code.
The function may be slightly simplified:
sub trim { @_ = @_ ? @_ : $_ if defined wantarray; s/^\s+//, s/\s+$// for @_ ? @_ : $_; wantarray ? @_ : shift }
The first two lines can be collapsed into one, since they do the same thing (assigning @_ ) only with different source values. And there is no need for external verification of return ... if defined wantarray at the end, since returning a value in a void context does nothing.
But would I probably change the last line to wantarray ? @_ : pop wantarray ? @_ : pop , as this makes it behave like a list (the last element in a scalar context).
After everything is said and done, it allows you to use the following types of calls:
my @test_array = ( 'string1', ' string2', 'string3 ', ' string4 '); my @result = trim @test_array; my $result = trim $test_array[0]; trim @test_array; # in place trim
and even supports a call loop:
my @result = map trim, @test_array;
or in more detail:
my @result = map trim($_), @test_array;
and it can be used inside a while loop similar to chomp
while (<$file_handle>) { trim; # do something }
Opinions about dwimmery in Perl are mixed. I personally like it when the functions give me the ability to encode the caller in a way that makes sense, rather than working with a hard interface function.