Home > Back-end >  select an array inside the perl script using $ARGV[]
select an array inside the perl script using $ARGV[]

Time:09-23

In my perl script I have multiple arrays and I have to decide which array to choose while executing the script using $ARGV[] and then that array I have to use in an foreach statement.

I have tried :

@array_1 = ("abc", "home", "city");
@array_2 = ("state", "planet", "stars");
foreach my $string ($ARGV[0]) {
    print "$string \n";
}

but this doesn't works as i need .

CodePudding user response:

How about using an array of arrays? Then you would enter a number for the array you want, e.g. perl foo.pl 0 for array_1, and 1 for array_2.

use strict;
use warnings;   # always use these

my @array_1 = ("abc", "home", "city");
my @array_2 = ("state", "planet", "stars");
my @lookup = (\@array_1, \@array_2);
my @selected = @{ $lookup[$ARGV[0]] };
foreach my $string (@selected) {
    print "$string \n";
}

Or perhaps a hash? perl foo.pl a1 for array_1.

my %lookup = ( a1 => [ "abc", "home", "city" ],
               a2 => [ "state", "planet", "stars" ]);
my @selected = @{ $lookup{$ARGV[0]} };
foreach my $string (@selected) {
    print "$string \n";
}

The hash solution makes sense if you have some valid categories, like for example:

my %lookup = (  fruit => [ qw(apple orange pear) ],
                cars  => [ qw(ford honda ferrarri) ],
                colours => [ qw(blue red yellow) ]);
  •  Tags:  
  • perl
  • Related