in reply to RFC: Sub::Hashwrap - Use named arguments with any sub

I like this a lot, and I'm using it tomorrow (well, Monday). I often want to do this, but I also quite often want to have the flexibility to call the sub with either a hash or an array - for example when I have a sub which sometimes gets by on just one argument, or sometimes needs a whole load of stuff specified. So I favour the following tweak-ette (which I agree is making a boldish assumption that the user wd have to be aware of, namely that if *all* the named args are missing, that's not because we completely ballsed it up, but because we're submitting an array).
*{$sub} = sub { my %args = $wrapper{ hashref } ? %{$_[0]} : @_; my @orig_args; my @missing_args; foreach my $arg_name ( @{$wrapper{ names }} ) { if ( exists $args{ $arg_name } ) { push @orig_args, $args{ $arg_name }; } elsif ( exists $wrapper{ default }{ $arg_name } ) { push @orig_args, $wrapper{ default }{ $arg_name }; } else { push @missing_args, $arg_name; } } if (@missing_args == 0) { return $orig_sub->( @orig_args ); } elsif (@missing_args == @{$wrapper{ names }}) { return $orig_sub->( @_ ); } else { croak("Cannot find value or default for arg(s) '" . (join +"', ", @missing_args) . "'"); } }
My only other observation is that it raises a "Subroutine redifined" warning - my grasp of name space issues is too weak to know whether that can be avoided. But I must say, I like it.

§ George Sherston