所以我有一個簡單的Perl函數,我已經有一段時間了,並且想要擴展它,這是我想到的,這是我應該建立我的函數來處理可選參數?這是構建Perl子例程的方式嗎?
原文:
sub ucwords{
$str = @_[0];
$str = lc($str);
$str =~ s/\b(\w)/\u$1/g;
return $str;
}
擴展:
sub ucwords{
if(@_[0] ne undef){#make sure some argument was passed
@overloads = (0,1,2,3);
$str = @_[0];
if(@_[1] eq undef || @_[1] eq 0){ #default is to lowercase all but first
$str = lc($str);
$str =~ s/\b(\w)/\u$1/g;
return $str;
}else{ #second parameters
if(!grep $_ eq @_[1], @overloads){ die("No overload method of ucwords() takes "[email protected]_[1]." as second parameter."); }
if(@_[1] eq 1){ $str =~ s/\b(\w)/\u$1/g;} #first letter to upper, remaining case maintained
if(@_[1] eq 2){ $str = lc($str); $str =~ s/(\w)\b/\u$1/g;} #last letter to upper, remaining to lower
if(@_[1] eq 3){ $str =~ s/(\w)\b/\u$1/g;} #last letter to upper, remaining case maintained
return $str;
}
}else{
die("No overload method of ucwords() takes no arguments");
}
}
精神科
tl; dr,但是不是你的代碼只是做這個? 'join''map {ucfirst} split /(\ s +)/ $ string'? – Ether 2009-10-15 16:42:48
@Psytronic你應該閱讀'perldoc perlsub':http://perldoc.perl.org/perlsub.html – 2009-10-15 16:45:25
感謝您的建議,我並不特別尋找關於功能本身的評論,但我知道有可能更好做這項工作的方式,這是關於我建立它的方式的更多評論,因爲我不想從一開始就做錯事,反覆重複。 – Psytronic 2009-10-16 07:23:05