Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Given a list of pairs the variable names matching the keys will automagically be assigned to the corresponding values.

I'd had it in the back of my mind that this could be achieved fairly simply, as demonstrated below, but as you can see it's not the most robust of methods. I'll CPAN-ify it if anyone wants a rather more sensible version of the code, and I'm sure documentation and tests wouldn't go amiss too.

Update: This code can now be found on CPAN going under the guise of Params::Named.

use strict; use warnings; use PadWalker 'peek_sub'; use List::Util 'first'; ## Map named arguments to variables of those names. sub getargs { my %args = do { package DB; () = caller 1; @DB::args }; my $vals = peek_sub \&{(caller 1)[3]}; my %res = map { $_ => $args{substr($_, 1)} } grep exists $args{substr($_, 1)}, keys %$vals; my %map = map { my $orig_arg = \$_; my($ref_name) = first { $orig_arg == $vals->{$_} } keys %$vals; $ref_name => $orig_arg; } @_; ${ $map{$_} } = $res{$_} for keys %res; return \%res; } ## Basic test of getargs(); sub foo { getargs my($this, $that, $theother); print "this is: $this\nthat is: $that\nand the other is: $theother\n +"; } ## Have these pairs mapped to variables of the same name. foo this => "an argument", that => "used to refer to things", theother => "is something else altogether";

In reply to Named arguments in Perl5. Sorta. by broquaint

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-25 13:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found