I was trying to write a small perl script to understand Getopt::Long
.
Below is the script:
#!/usr/bin/perl
use strict;
use Getopt::Long;
my $op_type = "";
my @q_users;
GetOptions (
'query' => $op_type = "query",
'create' => $op_type = "create",
'modify' => $op_type = "modify",
'delete' => $op_type = "delete",
'user=s' => \@q_users
) or usage ("Invalid options.");
print "operation : $op_type\n";
When i ran this script as shown below:
$ ./all_opt.pl --query
operation : delete
I am assuming that am missing some kind of break statment in my program. I was expecting operation : query
as the result.
Please let me know what i am missing here.
You were very close, but I think you slightly misread the Getopt::Long documentation. Any code that you want to run when an option is found needs to be in a subroutine.
#!/usr/bin/perl
use strict;
use Getopt::Long;
my $op_type = "";
my @q_users;
GetOptions (
'query' => sub { $op_type = 'query' },
'create' => sub { $op_type = 'create' },
'modify' => sub { $op_type = 'modify' },
'delete' => sub { $op_type = 'delete' },
'user=s' => \@q_users
) or usage ("Invalid options.");
print "operation : $op_type\n";
Note that I've just added sub { ... }
around your existing $op_type = '...'
code.