a. 打破这条线,因为它没有:
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 s 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 bit tedious with all of the wantarray
checks, but the result is a function that shares a level of flexibility with Perl s builtin functions. The net result of making the function "smart" is to clean up the call site (avoiding looping constructs, temp variables, repetition, ...) which depending on the frequency the function is used can meaningfully improve code readability.
职能可以简化:
sub trim {
@_ = @_ ? @_ : $_ if defined wantarray;
s/^s+//, s/s+$// for @_ ? @_ : $_;
wantarray ? @_ : shift
}
头两条线可以滚动为一线,因为它们正在采取相同的做法(签署为@_
)与不同的来源价值相同。 没有必要在“外部<代码>返回......”中进行最后的“意向”检查,因为如果在真空环境中恢复价值,就没有任何进展。
但我可能把最后一行改为<代码>wantarray ? @_:pop,因为这样,它就象一个清单(斜体内的最后一点)。
一旦说到并做所有工作,便可使用以下称呼方式:
my @test_array = ( string1 , string2 , string3 , string4 );
my @result = trim @test_array;
my $result = trim $test_array[0];
trim @test_array; # in place trim
甚至仍然支持点火:
my @result = map trim, @test_array;
或大于:
my @result = map trim($_), @test_array;
可在与<代码>chomp类似的同时使用。
while (<$file_handle>) {
trim;
# do something
}
人们对Perl的游泳现象的看法好坏参半。 我个人喜欢这样,当职能赋予我灵活性,使打电话者具有某种意义,而不是围绕职能僵硬的接口开展工作。