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

In reply to Re: RFC: Sub::Hashwrap - Use named arguments with any sub by George_Sherston
in thread RFC: Sub::Hashwrap - Use named arguments with any sub by Ovid

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.