qazwart has asked for the wisdom of the Perl Monks concerning the following question:
Originally, I had a series of if/elsif statements to check the type of entry against a particular subroutine. Something like this:
This worked, but it created really long bits of code. Plus, if I created a new "type", I would have to go into my code, and change the if/elsif statements. Therefore, I am attempting to switch to this:if ($type == "INTEGER") { $convAnswer = checkInteger($answer); } elsif ($type eq "DATE") { $convAnswer = checkDate($answer); } elsif ($type eq "IPADDRESS") { $convAnswer = checkIpaddress($answer); } elsif ($type eq "FOO") { $convAnswer = checkFoo($answer); } else { die qq(There is no such type as "$type"\n); }
The good news is that this makes my program easier to maintain and understand because I've eliminated dozens of lines of testing data types and seeing which routine is needed. To add a new variable type, I simply have to define a new routine.my $sub = "check" . ucfirst(lc($type)); if (not defined (&{$sub}) { die qq(There is no such type as "$type"\n); } $convAnswer = &{$sub}($answer);
The bad news is that this fails if I have "strict 'refs'" invoked. I could do this:
And that works, but I feel there should be a better way without turning off strict "refs".my $sub = "check" . ucfirst(lc($type)); if (not defined (&{$sub}) { die qq(There is no such type as "$type"\n); } no strict "refs"; $convAnswer = &{$sub}($answer); use strict "refs"
Is there a better way of doing this? I was thinking of putting the check inside an eval block and then seeing if the eval succeeds or fails. However, I think this makes the code even more difficult to understand, so I would prefer to be able to use subroutine references if possible.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Trying to get around the "use strict 'refs'" Issue
by derby (Abbot) on May 07, 2007 at 17:25 UTC | |
|
Re: Trying to get around the "use strict 'refs'" Issue
by FunkyMonk (Bishop) on May 07, 2007 at 17:38 UTC | |
by naikonta (Curate) on May 08, 2007 at 14:03 UTC | |
by qazwart (Scribe) on May 07, 2007 at 17:54 UTC | |
by chromatic (Archbishop) on May 07, 2007 at 18:27 UTC | |
by blazar (Canon) on May 07, 2007 at 18:48 UTC | |
|
Re: Trying to get around the "use strict 'refs'" Issue
by thezip (Vicar) on May 07, 2007 at 17:26 UTC | |
|
Re: Trying to get around the "use strict 'refs'" Issue
by GrandFather (Saint) on May 07, 2007 at 22:06 UTC |