How to parse quoted as well as unquoted arguments in Perl?
I want my perl script to correctly parse two command line arguments separated by a space into two variables:
$ cat 1.pl
print "arg1 = >$ARGV[0]<\n";
print "arg2 = >$ARGV[1]<\n";
$ perl 1.pl a b
arg1 = >a<
arg2 = >b<
$ perl 1.pl "a b"
arg1 = >a b<
arg2 = ><
$
Is there a generic way of dealing with this rather than trying to detect whether开发者_C百科 quotes were used or not?
The data is passed to Perl by the shell.
program a b
will senda
andb
program 'a b'
will senda b
program "a b"
will senda b
program a\ b
will senda b
Perl has, AFAIK, no way of telling the difference between any of the last three.
You could split
every argument on spaces, and that would get the effect you are describing … but it would mean working in a different way to every other application out there.
Quentin's answer is not quite right for Windows.
Meanwhile, if you want to parse switches, Getopt::Long is best for that. But if you have two non-switch arguments, you could try this brute-force method:
my @args = map { split ' ' } @ARGV;
die usage() unless @args == 2;
or this:
die usage()
unless (
my ( $arg1, $arg2 )
= @ARGV == 1 ? ( split ' ', $ARGV[0], 3 )
: @ARGV == 2 ? @ARGV
: ()
) == 2
;
Here, die usage()
is just an pseudo-code.
精彩评论