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

Hi

Is it possible to make a 3rd command line argument optional and then execute a command if certain condition is met?

my $pkgname = $ARGV[0]; my $envname = $ARGV[1]; chomp; s/^\s+|\s+$//g; # trim spaces ##optional 3rd command line argument my $id = $ARGV[2]; chomp $id; if (not defined $id) { ($bquery eq $bfquery1) } else { ($bquery eq $bfquery2) }

Replies are listed 'Best First'.
Re: Make command line argument optional
by Athanasius (Archbishop) on Jul 10, 2018 at 02:46 UTC

    Hello TonyNY,

    You should always code with

    use strict; use warnings;

    at the head of your script, in which case, if $ARGV[2] is undefined, the statement chomp $id; will generate a warning. So the correct logic is:

    use strict; use warnings; my ($pkgname, $envname, $id) = @ARGV; if (defined $id) { chomp $id; print "Third argument: >$id<\n"; } else { print "No third argument\n"; }

    BTW, these statements:

    chomp; s/^\s+|\s+$//g; # trim spaces

    operate on the default variable $_, which is not initialised in the code snippet you show.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      I was ale to accomplish what I need to do by using the following. Thanks for your help.

      my $id = $ARGV[2]; if (not defined $id) { print "$id is not defined"; } else { print "$id is defined"; }

        I suspect you want

        if (not defined $id) { print '$id is not defined';
        Notice the change in quotes, inside double quotes $id will try to interpolate, and it is undefined

Re: Make command line argument optional
by AnomalousMonk (Archbishop) on Jul 10, 2018 at 02:36 UTC
Re: Make command line argument optional
by AnomalousMonk (Archbishop) on Jul 10, 2018 at 03:03 UTC
    my $id = $ARGV[2]; chomp $id;

    I don't understand how you intend to get something into  $ARGV[2] and thence into  $id that can then be chomp-ed off of it. Will you be playing perverse games with the  $/ special variable? What's really going on here?


    Give a man a fish:  <%-{-{-{-<

Re: Make command line argument optional
by Anonymous Monk on Jul 10, 2018 at 15:15 UTC
    Would the @ARGV array actually contain anything that needs chomp-ing?

      "sundial", how does such a comment even begin to help the OP with his question?