Search code examples
perlgetopt-long

Can Getopt::Long accommodate variable option names?


I am writing a script that can do something like:

script-name --resource1=xxx --resource2=xxx

But this can go up to 50+. Is there a way to make GetOpt accept dynamic option names?


Solution

  • What about auto-generating the options list for Getopt::Long like example below? Since the list of options will be likely pretty long, using Getopt::ArgvFile allow you to supply configuration file with options instead of specifying them on command-line.

    use Getopt::Long;
    use Getopt::ArgvFile;
    use Data::Dump;
    
    my @n = (1 .. 10);    # how many resources allowed
    my %opts = (
        port                  => ':i',
        http_version          => ':s',
        invert_string         => ':s',
        ssl                   => '',
        expect                => ':s',
        string                => ':s',
        post_data             => ':s',
        max_age               => ':i',
        content_type          => ':s',
        regex                 => ':s',
        eregi                 => ':s',
        invert_regex          => '',
        authorization         => ':s',
        useragent             => ':s',
        pagesize              => ':s',
        expected_content_type => ':s',
        verify_xml            => '',
        rc                    => ':i',
        hostheader            => ':s',
        cookie                => ':s',
        encoding              => ':s',
        max_redirects         => ':i',
        onredirect_follow     => ':i',
        yca_cert              => ':s',
    );
    
    my %args = ();
    GetOptions(\%args,
        map {
            my $i = $_;
            ( "resource$i:s", map { "resource${i}_$_$opts{$_}" } keys %opts )
        } @n
    ) or die;
    
    dd \%args;