http://qs321.pair.com?node_id=1229390


in reply to Parsing command-line arguments in a sophisticated way.

Getopt::Long can parse command-line options from a string. So my proposal is to take all options as a string, split on --job, and then parse whatever was in front of it. Like this:

use strict; use warnings; use Getopt::Long qw(GetOptionsFromString); use Data::Dumper; my ($args, $job) = split /--job /, join( ' ', @ARGV ); my %opts; my $ret = GetOptionsFromString( $args, \%opts, "file=s", "dir=s" ); $opts{"job"} = $job if $job; print Dumper \%opts;

Replies are listed 'Best First'.
Re^2: Parsing command-line arguments in a sophisticated way.
by haukex (Archbishop) on Feb 05, 2019 at 09:17 UTC
    split /--job /, join( ' ', @ARGV );

    That doesn't seem particularly safe to me... see my suggestion here (combined with GetOptionsFromArray).

      Not sure what you mean with "not safe". It is quite literally what was requested.

        Not sure what you mean with "not safe". It is quite literally what was requested.

        The OP said "We allow to use every possible string and argument after `--job`." For me, that includes the string --job itself.

        use Data::Dump; my @argv = qw/ foo --job X --job Y --job Z /; my ($args, $job) = split /--job /, join( ' ', @argv ); dd $args, $job; __END__ ("foo ", "X ")

        Another one, a command line of --hello "world --job foo" --job bar:

        use Data::Dump; my @argv = ('--hello','world --job foo','--job','bar'); my ($args, $job) = split /--job /, join( ' ', @argv ); dd $args, $job; __END__ ("--hello world ", "foo ")