Avoiding mix of certain arguments to script
Asked Answered
A

1

7

I have a script which can get tens of arguments/flags using Getopt::Long. Certain flags are not allowed to be mixed, such as: --linux --unix are not allowed to be supplied together. I know I can check using an if statement. Is there is a cleaner and nicer way to do that?

if blocks can get ugly if I don't want to allow many combinations of flags.

Aniseikonia answered 24/4, 2012 at 13:34 Comment(0)
A
4

It does not seem that Getopt::Long has such a feature, and nothing sticks out after a quick search of CPAN. However, if you can use a hash to store your options, creating your own function doesn't seem too ugly:

use warnings;
use strict;
use Getopt::Long;

my %opts;
GetOptions(\%opts, qw(
    linux
    unix
    help
)) or die;

mutex(qw(linux unix));

sub mutex {
    my @args = @_;
    my $cnt = 0;
    for (@args) {
        $cnt++ if exists $opts{$_};
        die "Error: these options are mutually exclusive: @args" if $cnt > 1;
    }
}

This also scales to more than 2 options:

mutex(qw(linux unix windoze));
Asaph answered 24/4, 2012 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.