cLive ;-) has asked for the wisdom of the Perl Monks concerning the following question:
Hi all,
I have the feeling I'm reinventing the wheel here, so I thought I'd throw this one out.
I'm doing some code maintenance. One thing we've decided to do, is move towards all subs in modules being called with named args, rather than a list of scalars. There's no way I want to do this globally all at once, so I thought it might be fun to use a sub to help ease the changeover.
Another objective that comes with this is to list the expected args clearly at the beginning of each sub to improve readability.
So, I came up with this (skeletal code at the moment):
This does what I want, but requires me to add the clumsyuse strict; use warnings; use Data::Dumper; my $test = TestMod->new(); print "Correct, deprecated, list test:\n"; $test->test_sub('cLive ;-)',34,'curious'); print "Incorrect, deprecated, list test (too many args):\n"; $test->test_sub('cLive ;-)',34,'curious','bad arg'); print "Correct, hashref test:\n"; $test->test_sub({-name => "cLive ;-)", -age => "34", -mood => "curious"}); print "Incorrect, hashref test:\n"; $test->test_sub({-name => "cLive ;-)", -age => "34", -badarg => 1, -mood => "curious"}); exit(0); package TestMod; use strict; use warnings; sub new { return bless {}, ref $_[0] || $_[0]; } sub fix_args { my ($self,$arg)= @_; defined $arg->{-arg_names} or return {}; my @arg_names = @{$arg->{-arg_names}}; my @arg_values = @{$arg->{-arg_values}}; my $fixed_arg = {}; if (ref $arg_values[1] eq 'HASH') { # if hash, check no incorrect args sent $fixed_arg = $arg_values[1]; my %arg_test = %{$arg_values[1]}; delete $arg_test{$_} for (@arg_names); keys %{arg_test} and warn "Invalid argument sent to sub. Valid + args are: @arg_names" and return; } else { # array - map to keys, set to '' if not sent (backwards compat +ability with some subs). shift @arg_values; # "unbless" @arg_values>@arg_names and warn "Too many arguments!" and retu +rn; for (0..$#arg_names) { $fixed_arg->{$arg_names[$_]} = $arg_values[$_] || ''; } } return $fixed_arg; } sub test_sub { my $self = $_[0]; my $arg = $self->fix_args({ -arg_names => ['-name','-age','-mood'] +, -arg_values => \@_ }); print Data::Dumper::Dumper($arg),'-'x50,"\n"; }
to the beginning of each sub.my $arg = $self->fix_args({ -arg_names => ['-name','-age','-mood'] +, -arg_values => \@_ });
So, am I going about this the wrong way? Is there a better way of doing it?
What do you think?
cLive ;-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: code tidying - re-inventing the wheel?
by merlyn (Sage) on Jan 07, 2005 at 02:09 UTC | |
|
Re: code tidying - re-inventing the wheel?
by sgifford (Prior) on Jan 07, 2005 at 01:40 UTC | |
|
Re: code tidying - re-inventing the wheel?
by Fletch (Bishop) on Jan 07, 2005 at 08:53 UTC |