views:

90

answers:

3
  • I have 5 Perl files that are verification scripts for 5 different states of my environment.

    Each of them has at least a couple of subroutines.

  • Till now, the number of states was limited to 5 and these worked fine. But now, I have like 20 more states of the environment and hence 20 more Perl scripts according to the current design.

  • I want to move all the five scripts to just one script which takes the state as an argument and have 5 different subroutines for 5 different states.

    This way, when I need to add a verify for yet another state, I will just have to define a new subroutine instead of a whole new Perl script.

  • The problem is that it will mean using nested subroutines (which are known to run into issues), or unrolling the subroutines themselves.

For example,

original scripts

$ cat verify1.pl
sub a1 {
    ...
}
sub b1 {
    ...
}
a1(); b1(); a1();
$ cat verify2.pl
sub a2 {
    ...
}
sub b2 {
    ...
}
sub c2 {
    ...
}
a2(); b2(); c2(); a2();
$

consolidated script

$ cat verify.pl
sub one {
    ...
}
sub two {
    ...
}
my ($arg) = @ARGV;
if ($arg == 1) {
    one();  # should do what verify1.pl did
}
elsif ($arg == 2) {
    two();  # should do what verify2.pl did
}
$

What should I do to resolve this?

+2  A: 

You can place subroutines normally as the way they should be.

sub a1 {
    ...
}
sub b1 {
    ...
}
sub a2 {
    ...
}
sub b2 {
    ...
}
sub c2 {
    ...
}
sub one {
    a1(); b1(); a1();
}
sub two {
    a2(); b2(); c2(); a2();
}
my ($arg) = @ARGV;
if ($arg == 1) {
    one();  # should do what verify1.pl did
}
elsif ($arg == 2) {
    two();  # should do what verify2.pl did
}
Ruel
+5  A: 
sub one {
    do 'verify1.pl';
}
sub two {
    do 'verify2.pl';
}

In the long run, however, it is better to convert your scripts into modules in order to manage the complexity in a modern and sane fashion.

daxim
+1 for the advice to use module. See http://perldoc.perl.org/perlmod.html#Perl-Modules as a reference (but not as a tutorial).
dolmen
+1  A: 

I'd resolve this by just putting all the subroutines in one file and renaming any that conflict.

However, it sounds like your problem is that you're hardcoding for every possible validation situation that you might run into. The better way is to come up with a process where you can build validation pipelines dynamically. Since I don't know what you need, I don't know if something like Data::Constraint or the other validation modules would be right for you. It's extremely tough to give any sort of useful advice with so little information in the question.

brian d foy