user1987607 user1987607 - 7 months ago 24
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/test.pl -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
$command
variable that will be executed afterwards

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


Now here are two problems that I encounter:

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

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

Answer

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;

execute($command);

Also

  • 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