batmonk has asked for the wisdom of the Perl Monks concerning the following question:

I'm sorry if this is a FAQ, but I can't find it. Please consider:

#!/usr/bin/perl -w use strict; if (!@ARGV) {showhelp()} else { my $single = shift; my $remain = join( ' ', @ARGV ); print "First arg = $single\n"; print "Remaining = $remain\n"; } sub showhelp{ print <<"_HELP"; Trying to understand how Perl handles arguments Use: $0 First Second Third Fourth ... Nth Should output: First arg = First Remaining = Second Third Fourth ... Nth The idea is to save the first argument to a scalar and the remaining ones into a second scalar, with the space (and *only* a space) being used as a separator. _HELP }

When run, this works fine for:

%perl arg1.pl fred barney wilma First arg = fred Remaining = barney wilma

It returns the same result when the first argument contains a comma:

%perl arg1.pl fred,barney wilma First arg = fred Remaining = barney wilma

In the second case, I want $single to equal "fred,barney" and $remaining to equal "wilma". Can I do this? How? Why are commas considered separators? Is there a better way to do this? Thanks.

Replies are listed 'Best First'.
Re: Processing @ARGV using just spaces
by chipmunk (Parson) on May 17, 2001 at 22:06 UTC
    The parsing of the command line is a function of the shell, not of Perl. I don't know what shell you're using that treats commas in that way, but there's not much you can do about it in Perl.

    When I run your script in tcsh or bash, where comma is not a special character, I get the output you expected.

Re: Processing @ARGV using just spaces
by Anonymous Monk on May 17, 2001 at 22:14 UTC
    If changing shell is not possible, try quoting your arguments in the command line.

    e.g.
    perl arg1.pl 'fred,barney' wilma

    I'm not sure which shell you're using. For me, quoting on the command line helped me on other commands in csh.
Re: Processing @ARGV using just spaces
by cforde (Monk) on May 17, 2001 at 22:23 UTC
    It looks to me like your command interpreter (shell) is interpreting the parameters before Perl even sees the argument string. Try this to see what is happening:
    use strict; for (my $j = 0; $j <= $#ARGV; $j++) { print "ARGV[$j] = $ARGV[$j]\n"; }
    For instance:
    t.pl one,two three four ARGV[0] = one,two ARGV[1] = three ARGV[2] = four t.pl "one two" three four ARGV[0] = one two ARGV[1] = three ARGV[2] = four
    Notice that the command interpreter that I'm using has different "features" than yours...

    Have fun,
    Carl Forde