Variable Scope in Perl

I have to admit that i have not used Perl at all and this is a singular occasion where i have to patch an existing Perl script. I dearly hope i do not have to do it again for the next 15 years and therefore try to avoid having to learn the programming language in earnest.

The OS is AIX 7.1, the Perl Version is 5.01.

I have a script using a (user-written) library:

#!/usr/bin/perl

use warnings;
use strict;

use v5.10.1;    # state, say, given ...
use Vmax;

[...]

In the mentioned library "Vmax" there are some constants (well, at least they look to be constants for my untrained eye) declared. These are used further on in some subfunctions:

use v5.10.1;
use strict;
use warnings;

my %pg = ( $SIDS[0] => 'stringA',
           $SIDS[1] => 'stringB' );

[...]
sub work_pg
{
     [...]

     for my $sid (@SIDS)
     {
          say "INFO: do something with $pg{$sid}";
          my @cmd = ( 'command', [...], $pg{$sid}, [...] )
          RunCmd \@cmd, \$in, \$out, \$err, $LONG;
     }
}

This all works well. The "pg" array above represents port groups in two EMC VMax storage systems. As we added new port groups now i need to introduce a switch to the main program to select one set of port groups instead of using these two. Something like (pseudo-code):

case condition in
1) 
     my %pg = ( $SIDS[0] => 'stringA',
                $SIDS[1] => 'stringB' );

2) 
     my %pg = ( $SIDS[0] => 'stringC',
                $SIDS[1] => 'stringD' );

[...]
end case

Now i have already found out how to add a command line option to the main script but i am not sure how to pass this option to the library and how to tackle the problem with selecting the right set of array values depending on the options value.

I'd like to have the script to be called like this:

script -foo -bar ... -pg [1|2|3...]

and then select the corresponding value sets for pg[] in the called lib.

Thanks for your help.

bakunin

  1. There is no switch case feature in perl by default. So you may have to use if-elsif-else blocks. Or you could install the Switch.pm module and use switch case.

  2. To pass option to Vmax lib:

in main.pl:

use Vmax;
[...]

my $option = <option_from_command_line>;

Vmax::set_option($option);
Vmax::work_pg(<args>);
[...]

in Vmax.pm:

my $option = "";
sub set_option {
    $option = shift;
}

if ($option == 1) {
    %pg = ( ... );
}
elsif ($option == 2) {
    %pg = ( ... );
}
[...]

sub work_pg {
    [...]
}

Please correct me if you find a better method. Thanks.

1 Like

Since Perl 5.10 is being used, the given statement can do the work of a switch.

given($option) {
   when(1) { %pg = (...)}
   when(2) { %pg = (...)}
   when(3) { %pg = (...)}
   default { say "Unexpected value given"; }
}
1 Like