Lazer
Lazer

Reputation: 94800

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 quotes were used or not?

Upvotes: 1

Views: 291

Answers (2)

Axeman
Axeman

Reputation: 29844

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.

Upvotes: 1

Quentin
Quentin

Reputation: 943108

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.

Upvotes: 10

Related Questions