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 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:
or this:
Here,
die usage()
is just an pseudo-code.