in reply to Mixing command line arguments

Simply redefine the prefix:
use Getopt::Long; Getopt::Long::Configure('prefix_pattern=(?:--|-)?'); $rv = GetOptions( 'help|h!' => \$help, 'b!' => \$backup, 'u!' => \$upd_sybase, 's!' => \$silent, 'update' => \$update, 'server=s' => \$server, 'user=s' => \$user, 'password=s' => \$password, ); push(@args, $help ? "--help" : "--nohelp") if defined $help; push(@args, $backup ? "--b" : "--nob" ) if defined $backup; push(@args, $upd_sybase ? "--u" : "--nou" ) if defined $upd_sybase; push(@args, $silent ? "--s" : "--nos" ) if defined $silent; push(@args, "update" ) if defined $update; push(@args, "server=$server" ) if defined $server; push(@args, "user=$user" ) if defined $user; push(@args, "password=$password" ) if defined $password; print(join(' ', @args), $/);

Replies are listed 'Best First'.
Re^2: Mixing command line arguments
by revdiablo (Prior) on Nov 02, 2004 at 18:04 UTC

    I realize this wasn't an integral part of your example, but your series of push lines would be very disheartening for me to see in real code. For something like that, I'd much rather see a data-driven solution. Something along the lines of:

    my @args; my %chkopts = ( help => $help, b => $backup, u => $upd_sybase, s => $silent, ); while (my ($k, $v) = each %chkopts) { next unless defined $v; push @args, $v ? "--$k" : "--no$k"; } my %chkargs = ( update => $update, server => $server, user => $user, password => $password, ); while (my ($k, $v) = each %chkargs) { next unless defined $v; push @args "$k=$v"; }

    This way, the data (i.e., which args and opts need to be checked, and what their values are) is separated from the policy (i.e., build an array holding the defined args/opts and their values, using a certain syntax for args and a different syntax for opts). Adding new args or opts would be a much simpler process, and checking the data for errors would be easier. At some point, this data could even be moved out of the code altogether, and put in a config file.