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

I'm trying to have default data in case a command line argument is missing.
There must be a better way of doing this...
my $fileold = "ArchLDAP"; my $filenew = "LDAP"; my $infileold = $ARGV[0]; if ($infileold eq "") { $infileold = $fileold; } my $infilenew = $ARGV[1]; if ($infilenew eq "") { $infilenew = $filenew; }
Your humble servant
-Chuck

Replies are listed 'Best First'.
Re: Defaults for command line args
by btrott (Parson) on May 15, 2000 at 22:25 UTC
    How about:
    my $infileold = $ARGV[0] || $fileold; my $infilenew = $ARGV[1] || $filenew;
    Or, if you want to get rid of those args from @ARGV, you could use shift:
    my $infileold = shift || $fileold; my $infilenew = shift || $filenew;
RE: Defaults for command line args
by vroom (His Eminence) on May 15, 2000 at 22:26 UTC
    That's what ||= is for.
    $infile ||= "blah"; #this will only set $infile="blah" when $infile is undefined.
    Or there's always
    $infile= ? $infile : "default";


    vroom | Tim Vroom | vroom@cs.hope.edu
RE: Defaults for command line args
by mikfire (Deacon) on May 15, 2000 at 22:26 UTC
    Try something like this:
    my $fileold = "ArchLDAP"; my $filenew = "LDAP"; my $infileold = $ARGV[0] || $fileold; my $infilenew = $ARGV[1] || $filenew;
    Mik
    Mik Firestone ( perlus bigotus maximus )
Re: Defaults for command line args
by lhoward (Vicar) on May 15, 2000 at 23:51 UTC
    For more complicated command-line argument parsing you may want to check out the Getopt::Long and Getopt::Std modules.
Re: Defaults for command line args
by mdillon (Priest) on May 15, 2000 at 22:26 UTC
    this isn't really "better", but it looks nicer:
    my $infileold = (@ARGV) ? shift @ARGV : "ArchLDAP"; my $infilenew = (@ARGV) ? shift @ARGV : "LDAP";
      The problem with this is that @ARGV could be non-empty but its elements could be undef or empty strings. So your test for "if (@ARGV)" would pass, but the variable would get assigned an empty string. Consider what happens if the scripts is called like this:
      ./prog.pl ""
      In this case @ARGV is not empty, but its first element is an empty string.

      --ZZamboni

        yeah, i thought of that, but i was over editing my answer when i saw three other answers which together covered every aspect of the problem. i think the best is btrott's solution:
        my $infileold = shift || $fileold;