user1987607 user1987607 - 1 year ago 113
Perl Question

perl parse command line arguments using shift command

I have a question regarding parsing command line arguments and the use of the shift command in Perl.

I wanted to use this line to launch my Perl script

/home/scripts/ -a --test1 -b /path/to/file/file.txt

So I want to parse the command line arguments. This is part of my script where I do that

if ($arg eq "-a") {
$main::john = shift(@arguments);
} elsif ($arg eq "-b") {
$main::doe = shift(@arguments);

I want to use then these arguments in a
variable that will be executed afterwards

my $var1=$john;
my $var2=$doe;
my $command = "/path/to/tool/tool --in $line --out $outputdir $var1 $var2";

Now here are two problems that I encounter:

It should not be obligatory to specify
at the command line. But what happens now is that when I don't specify
, I get the message that I'm using an uninitialized value at the line where the variable is defined

Second problem:
will now equal
so it will be in this case
. However I want
to be equal to
--text /path/to/file/file.txt
. Where should I specify this
. It cannot be standardly in the
, because then it will give a problem when I don't specify
. Should I do it when I define
, but how then?

Answer Source

You should build your command string according to the contents of the variables

Like this

my $var1 = $john;
my $var2 = $doe;
my $command = "/path/to/tool/tool --in $line --out $outputdir";

$command .= " $var1"        if defined $var1;
$command .= " --text $var2" if defined $var2;



  • Don't use ampersands & when you are calling Perl subroutine. That hasn't been good practice for eighteen years now

  • Don't use package variables like $main:xxx. Lexical variables (declared with my) are almost all that is necessary

  • As Alnitak says in the comment you should really be using the Getopt::Long module to avoid introducing errors into your command-line parsing

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download