Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

broquaint (2964)

broquaint
  (email not shown publicly)

Journal of broquaint (2964)

Tuesday October 04, 2005
09:16 AM

Named arguments on Perl5. Sorta.

[ #27013 ]
Here's a little bit of madness I cooked up for using named arguments natively in perl5:

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";

This will output:

this is: an argument
that is: used to refer to things
and the other is: is something else altogether

So, as you can see, given a list of pairs the variable names matching the keys will be automagically assigned to the corresponding values.

I'd had it in the back of my mind that this could be achieved fairly simply, as demonstrated above, 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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.