Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A question about Getopt::Long..GetOptions 1

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
I know how to correctly use Getopt::Long..GetOptions to parse cmdline args.

But I do not know how to print out the actual cmdline args before my script exits.

The interface is quite complicated and the logs are long. It would be nice to print out the actual cmdline args so we know exactly what to expect in the logs.

I would guess there should be something like @ARGV in GetOptions(). I tried %Options but it did not work.

So, briefly, is there a global variable in Getopt::Long..GetOptions that still holds all cmdline args like @ARGV?

Thanks.

 
Post some of the code you're working with. Specifically where you call GetOptions.
 
Ok, I finally have some time to revisit this thread. Here is my sample code. My question is whether there is a way to get @ARGV or something similar when GetOptions() is called?
Code:
#!/usr/bin/perl -w

use Getopt::Long;

my $debug = 0;
my $flag;
[COLOR=red]GetOptions("flag=s"=>\$flag, "d"=>\$debug);[/color]
print "$0 #@ARGV#\n"; # @ARGV is not defined when GetOptions() is called
print "\$flag = $flag\n" if($flag);
print "\$debug = $debug\n" if($debug);

% ./test.pl -d -flag 2
[b][COLOR=blue]./test.pl ##[/color][/b]
$flag = 2
$debug = 1
As shown in blue of the output, ‘@ARGV’ is not defined.
Run it again when the red line is commented out:
Code:
% ./test.pl -d -flag 2
[b][COLOR=blue]./test.pl #-d -flag 2#[/color][/b]
This time, ‘@ARGV’ is defined when GetOptions() is not called.

So, again, how to get something similar with ‘@ARGV’ when GetOptions() is used? Thanks.
 
@ARGV contains all the command line arguements prior to your call to GetOptions - the arguments are parsed and removed from @ARGV by the function. Probably the easiest way would be to make a copy of @ARGV before you make the GetOptions call. Something like:
Code:
use Getopt::Long;

my @cmd_line = @ARGV;
my $debug = 0;
my $flag;
GetOptions("flag=s"=>\$flag, "d"=>\$debug);
#print "$0 #@ARGV#\n"; # @ARGV is not defined when GetOptions() is called
print "$0 #@{cmd_line}#\n";
print "\$flag = $flag\n" if($flag);
print "\$debug = $debug\n" if($debug);
I also noticed in the documentation for Getopts::Long, you can use GetOptionsFromArray to parse an arbitrary array. You could feed it @cmd_line (from the example above) or any copy of @ARGV and preserve @ARGV if that is your preference.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top