test data test data - 22 days ago 6
Perl Question

Why the following code shows an error?

I want to pass arguments from the command line so i had tried the following code but it throws an error?

use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use Getopt::Std;
print "raw data:@ARGV\n";
my $site=getopts('bangalore','norwood','limerick');
if($site)
{
print "success";
}
else
{
die "error";
}
print "final data:@ARGV \n";

Answer

Your code is not correct. Please go through the documentation first: http://perldoc.perl.org/Getopt/Long.html

Below is an attempt to guess what you were trying to achieve.

use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $city;
print "raw data:@ARGV\n";
GetOptions ("city=s" => \$city) or die("Error in command line arguments\n");
my $site = $city;
if($site){
    print "success: City is $city\n";
}
print "Final data:@ARGV \n";

Output:

chankeypathak@stackoverflow:~/Desktop$ perl test.pl -city=bangalore
raw data:-city=bangalore
success: City is bangalore
Final data: 

Output when passed incorrect param:

chankeypathak@stackoverflow:~/Desktop$ perl test.pl -blah=blah
raw data:-blah=blah
Unknown option: blah
Error in command line arguments
Comments