打破了由線下來行是因爲它一直沒有:
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]
}
我同意代碼變得有點乏味與所有wantarray
檢查,但結果是共享一個級別的功能Perl內置函數的靈活性。使函數「聰明」的最終結果是清理調用站點(避免循環構造,臨時變量,重複...),這取決於函數的使用頻率,可以有效地提高代碼的可讀性。
功能可以簡化一點:
sub trim {
@_ = @_ ? @_ : $_ if defined wantarray;
s/^\s+//, s/\s+$// for @_ ? @_ : $_;
wantarray ? @_ : shift
}
前兩行可以集於一身,因爲他們都在做同樣的事情(分配給@_
)只是用不同的源值。並且最後不需要外部return ... if defined wantarray
檢查,因爲在void上下文中返回值無論如何都不會執行任何操作。
但我可能會在最後一行更改爲,因爲這使得它像一個列表(在標量上下文最後一個元素)。
一旦所有說,做,這允許使用下列調用樣式:
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;
它可以在類似於的while循環中使用3210
while (<$file_handle>) {
trim;
# do something
}
關於dwimmery在Perl中的觀點有很多。我個人喜歡它,當函數爲我提供了靈活的編碼調用方法,而不是圍繞函數的嚴格界面工作。
爲什麼你想離開地圖給用戶,而你可以將它抽象出來? – 2012-01-16 10:03:19
相關:[在Perl修剪](https://plus.google.com/105725977711317285348/posts/ienzxqHJmRe) – daxim 2012-01-16 11:33:15
wantarray和類似魔屎是疫病。除非必須,否則不要做聰明的編程。永遠不要聰明的API。 – tsee 2012-01-16 20:02:29