So I've had a simple ucwords function for Perl which I've had a while, and wanted to expand it, this is what I've come up with, is this the way I should be building my functions to handle optional parameters?
Original:
sub ucwords{
$str = @_[0];
$str = lc($str);
$str =~ s/\b(\w)/\u$1/g;
return $str;
}
Extended:
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");
}
}
Psy