Lazer
Lazer

Reputation: 95000

Should I use nested subroutines in Perl?

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?

Upvotes: 0

Views: 1433

Answers (3)

brian d foy
brian d foy

Reputation: 132920

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.

Upvotes: 1

daxim
daxim

Reputation: 39158

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.

Upvotes: 5

Ruel
Ruel

Reputation: 15780

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
}

Upvotes: 2

Related Questions