Search code examples
perlgetopt-long

How do I retrieve the exact value passed as an option value using Getopt::Long?


I am trying the Getopt::Long module to read command line arguments, but for some reason when I try to print the variable in a print statement it prints '1' and not the value that has been passed to the variable.

Example:

use Getopt::Long;
use warnings;
GetOptions(
                'name1' => \$name,
                'address' => \$add,
                'phone' => \$phone
        );
print "My name is $name , My address is $add, My phone number is $phone\n"

After running the above code with the following command:

perl getopt.pl --phone 77881100 --name1 Mart --address Ecity

The output is:

My name is 1 , My address is 1, My phone number is 1

I expected the output to be:

My name is Mart , My address is Ecity, My phone number is 77881100

Solution

  • use warnings;
    use strict;
    use Getopt::Long;
    GetOptions(
        'name1=s'   => \my $name,
        'address=s' => \my $add,
        'phone=s'   => \my $phone
    );
    print "My name is $name, My address is $add, My phone number is $phone\n"
    

    see the section Getopt::Long section Options with values