How to parse quoted as well as unquoted arguments

2019-08-11 05:15发布

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?

2条回答
疯言疯语
2楼-- · 2019-08-11 05:31

The data is passed to Perl by the shell.

  • program a b will send a and b
  • program 'a b' will send a b
  • program "a b" will send a b
  • program a\ b will send a 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.

查看更多
聊天终结者
3楼-- · 2019-08-11 05:38

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.

查看更多
登录 后发表回答