Search code examples
perlgetopt-long

How to get array of hash arguments using Getopt::Long lib in perl?


I want to take arguments as an array of hashes by using Getopt::Long in my script. Consider the following command line example:

perl testing.pl --systems id=sys_1 ip_address=127.0.0.1 id=sys_2 ip_address=127.0.0.2

For the sake of simplicity, I'm using two systems and only two sub arguments of each system, i.e., id and ip_address. Ideally, the number of systems is dynamic; it may contain 1, 2 or more and so with the number of arguments of each system.

My script should handle these arguments in such a way that it will store in @systems array and each element will be a hash containing id and ip_address.

Is there any way in Getopt::Long to achieve this without parsing it myself?

Following is pseudocode for what I'm trying to achieve:


testing.pl

use Getopt::Long;
my @systems;
GetOptions('systems=s' => \@systems);
foreach (@systems) {
  print $_->{id},' ', $_->{ip_address};
}

Solution

  • Here is an attempt, there might be more elegant solutions:

    GetOptions('systems=s{1,}' => \my @temp );
    
    my @systems;
    while (@temp) {
        my $value1 = shift @temp;
        $value1 =~ s/^(\w+)=//; my $key1 = $1;
        my $value2 = shift @temp;
        $value2 =~ s/^(\w+)=//; my $key2 = $1;
        push @systems, { $key1 => $value1, $key2 => $value2 };
    }
    
    for (@systems) {
        print $_->{id},' ', $_->{ip_address}, "\n";
    }
    

    Output:

    sys_1 127.0.0.1
    sys_2 127.0.0.2