Perl Programming Perl Subroutines: Arguments and Values |
Use definedness or existence to test for missing arguments. It’s a common mistake to use a boolean test to probe for missing arguments: Readonly my $FILLED_USAGE => 'Usage: filled($text, $cols, $filler)'; sub filled { croak $FILLED_USAGE # [etc.] The problem is that this approach can fail in subtle ways. If, for example, the filler character is'0'or the text to be padded is an empty string, then an exception will incorrectly be thrown. A much more robust approach is to test for definedness: use List::MoreUtils qw( any ); sub filled { croak $FILLED_USAGE # [etc.] Or, if a particular number of arguments is required, and undef is an acceptable value for one of them, test for mere existence: sub filled { my ($text, $cols, $filler) = @_; Existence tests are particularly efficient because they can be applied before the argument list is even unpacked. Testing for the existence of arguments also promotes more robust coding, in that it prevents callers from carelessly omitting a required argument, and from accidentally providing any extras. Note that existence tests can also be used when some arguments are optional, because the recommended practice for this case—passing options in a hash—ensures that the actual number of arguments passed is fixed (or fixed-minus-one, if the options hash happens to be omitted entirely): sub filled { my ($text, $opt_ref) = @_; # Cols and fill char now passed as options # etc.
blog comments powered by Disqus |
|
|
|
|
|
|
|