【发布时间】:2010-12-07 02:05:14
【问题描述】:
所以我有一个简单的 Perl ucwords 函数,我已经有一段时间了,并且想扩展它,这就是我想出的,这是我应该构建我的函数来处理的方式可选参数?
原文:
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 ".@_[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");
}
}
心理
标签: perl function parameters user-defined-functions