Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Greetings monks,
I have a possible solution to a problem but I'm not sure that it is the most efficient (or correct!) way to go about it. Here's the problem. I've got some code which looked like this:
my %data_h = (previously calculated data); my @errors; # store errors here my @passed; # list items that passed the tests foreach (@list) { if ($condition{'a'} == 1) { # perform test A on $_ using data from %data_h # if it fails, add an error message and go on to # the next list item } if ($condition{'b'} == 1) { # perform test B on $_ using data from %data_h # if it fails, add an error message and go on to # the next list item } # and so on, with several other tests # if it survives all these tests... push @passed, $_; } if (@passed) { # etc.
I'm sure that it would be better to create a subroutine beforehand which could be customised according to what tests were required. This is my attempt to create such a sub:
# create some dummy subroutines sub test_A { } sub test_B { } # redefine them as real subs if the conditions # are right local *test_A = sub { my $x = shift; # perform test A on $x using data from %data_h # if it fails, add an error message and go on to # the next list item } if $condition{'a'} == 1; local *test_b = sub { my $x = shift; # perform test B on $x using data from %data_h # if it fails, add an error message and go on to # the next list item } if $condition{'b'} == 1; sub do_tests { my $to_test = shift; # depending on what is in the %condition hash, # these will either be a real subroutine or just a dummy test_A($to_test); test_B($to_test); } foreach (@list) { do_tests($_); push @passed, $_; }
This seems kinda clunky, and I also get warnings about the subroutines being redefined. Is there a better way of doing this?
Thanks a lot in advance for any advice!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: subroutines - creating a custom subroutine and 'subroutine redefined' errors
by FunkyMonk (Bishop) on Aug 14, 2007 at 09:48 UTC | |
|
Re: subroutines - creating a custom subroutine and 'subroutine redefined' errors
by BrowserUk (Patriarch) on Aug 14, 2007 at 10:46 UTC | |
by Anonymous Monk on Aug 14, 2007 at 12:46 UTC | |
|
Re: subroutines - creating a custom subroutine and 'subroutine redefined' errors
by moritz (Cardinal) on Aug 14, 2007 at 09:41 UTC |