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.
In reply to Trying to get around the "use strict 'refs'" Issue by qazwart
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |