I'm trying to extend Damians PBP advices for unpacking and then checking arguments using the ternary-operator ...
sub padded { my ($text, $arg_ref) = @_; # Set defaults... # If option given... Use option Else defau +lt my $cols = exists $arg_ref->{cols} ? $arg_ref->{cols} : $DEF_PAG +E_WIDTH; my $filler = exists $arg_ref->{filler} ? $arg_ref-> : $SPACE; # ... etc return $filler x $left . $text . $filler x $right; }
... by using the defined-or operator, which was new in 5.10 long after PBP was published.
It's more concise ... but actually I'm not sure how to handle named arguments¹ so which pattern do you think is better?
*** Unpack Named First
sub unpack_named_first { my ($pos1, $pos2 ,%arg) = @_; # unpack my ($name1, $name2) = @arg{'name1','name2'} $pos1 // die("Missing arg!"); # obligatory $pos2 //= 42; # default $name1 // die("Missing arg!"); # obligatory #$name2 # optional # ...etc }
*** Unpack Named Later
sub unpack_named_later { my ($pos1 ,$pos2 ,%arg) = @_; $pos1 // die("Missing arg!"); $pos2 //= 42; $arg{name1} // die("Missing arg!"); # if you need to unpack hash-args my ($name1,$name2) = @arg{qw/name1 name2/}; # ...etc }
*** Unpack Named On The Fly
sub unpack_named_on_the_fly { my ($pos1 ,$pos2 ,%arg) = @_; $pos1 // die("Missing arg!"); $pos2 //= 42; my $name1 = $arg{name1} // die("Missing arg!"); my $name2 = $arg{name2}; # ...etc }
My intentions are:
1. to have a concise pattern to replace the (alas) missing sub-signatures in perl
2. to follow more DRY practice
3. The patterns should be also usable in parts, i.e. further arg constraints could be extendable later, e.g. using ternaries
4. to have self-documenting code.
5. to be parsable for inspection and/or POD-creation and/or IDE-expansion.
a further extension could be to replace die() with a wrapper called missing(), which uses caller to pretty-print source-line and function-name.
Personally I tend to the first option to unpack first, even if it's more work to refactor if someone decides later that he needs to unpack %arg which he used directly before, ie. $arg{name}$pos1 // die_miss(); $pos2 // warn_miss();
Cheers Rolf
¹) please don't be confused:
1. at my current project we are not following Damian's advice to use an anonymous hash for named args.
2. testing for existence instead for definedness is such a rare special case that it should be explicitely coded.
|
|---|