-2

i wrote perl script that take argument from command line and print simple line with this argument. this is the code:

#!/usr/bin/perl -w
use Getopt::Long;
use strict;

my $aviad;


GetOptions(
            "aviad:s"  => \$aviad,
           );

if($aviad){
    printf ("aaa: $aviad\n");
}
else{
        printf("error\n");
}

i dont know why,but when i type the scriptname in command line like that:

./abc.pl aviad 4

i got error instead of aaa:4

Why it happened? and how can i solve it?

toolic
  • 57,801
  • 17
  • 75
  • 117
user3205436
  • 57
  • 1
  • 8
  • 3
    looks like you have to invoke your command like this: `./abc.pl --aviad 4` – leu Jun 01 '15 at 14:08
  • can i change something in the code for use command line without this signs? – user3205436 Jun 01 '15 at 14:12
  • 3
    Yes. Read from `@ARGV` – Sobrique Jun 01 '15 at 14:16
  • 1
    With Getopt::Long you can also say `abc.pl -a 4` as a short form of the long params. – simbabque Jun 01 '15 at 14:21
  • what is the meaning of "Read from @ARGV"?? – user3205436 Jun 01 '15 at 14:40
  • 1
    \@ARGV is an array of the arguments passed to a perl program. If you have 'perl test.pl 1 2 3 4' on the command line, you can reference the passed parameters (in test.pl) via \@ARGV. $ARGV[0] will equal 1, $ARGV[1] will equal 2 and so on. (ignore \ character above - trying to show perl syntax not send a message to a user) – gnuchu Jun 01 '15 at 14:52

1 Answers1

-1

catching key/value pairs from the command-line without getopt (hence without using dashes) can be done like this:

use strict;
use warnings;

my %opts = map { $ARGV[$_] => $ARGV[$_ + 1] } (grep {$_ % 2 == 0} 0..$#ARGV);

if($opts{'aviad'}) {
    printf("aaa:$opts{'aviad'}\n");
} else {
    printf("error\n");
}

this will print aaa:4 for invocations as the following:

perl myscript.pl aviad 4
perl myscript.pl bviad 23 aviad 4
perl myscript.pl cviad 12 aviad 4 bviad 23

A brief explanation:

grep {$_ % 2 == 0} 0..$#ARGV picks the even indices from @ARGV.

map { $ARGV[$_] => $ARGV[$_ + 1] } builds a hash where the even indices become keys and the odd ones the corresponding values.

leu
  • 2,051
  • 2
  • 12
  • 25