On Mon, Aug 06, 2001 at 06:35:43PM +0200, Louis Pouzin wrote:
> It looks as if Getopt::Std would fit my case, but I haven't yet been able
> to call it from my script. I seem not to understand how to pass it
> arguments.
While Scott is correct in his reply that MacPerl does not have a command
line, this is actually unimportant. Getopt::Std processes @ARGV to get
options, and it doesn't care whether @ARGV comes from the command line or
is set in the program, the way you did it.
> #!/usr/local/bin/perl -w
> $_='mbx2 5 -x tonus -a -x';
> $^O eq 'MacOS' && (@ARGV = split); # test mac/unix
> print "A argv= @ARGV\n";
> foreach (@INC) {print "C $_\n"}; #show library search
> use Getopt::Std;
> getopts 'ax:';
> print "E argv= @ARGV\n";
> print "opt_a=$opt_a\n";
> print "opt_x=$opt_x\n";
> __END__
> # Name "main::opt_x" used only once: possible typo.
> File 'PPC HD:Privat:MacPerl store:mini tests Ÿ:old:5-7'; Line 11
> # Name "main::opt_a" used only once: possible typo.
> File 'PPC HD:Privat:MacPerl store:mini tests Ÿ:old:5-7'; Line 10
Those warnings are to help you find typos, for example if you had a
variable named $member and you mispelled it $mebmer somewhere. Sometimes
you get them when you don't want them, though. To silence the warnings,
you can declare the variables ahead of time:
use vars qw/ $opt_a $opt_x /;
> A argv= mbx2 5 -x tonus -a -x
> C PPC HD:Privat:MacPerl store:MacPerl versions:MacPerl 5.20r4 Ÿ:lib:MacPPC:
> C PPC HD:Privat:MacPerl store:MacPerl versions:MacPerl 5.20r4 Ÿ:lib:
> C PPC HD:Privat:MacPerl store:MacPerl versions:MacPerl 5.20r4 Ÿ:lib:MacPPC:
> C PPC HD:Privat:MacPerl store:MacPerl versions:MacPerl 5.20r4 Ÿ:lib:
> C :
> C Dev:Pseudo:
> E argv= mbx2 5 -x tonus -a -x
> # Use of uninitialized value.
> File 'PPC HD:Privat:MacPerl store:mini tests Ÿ:old:5-7'; Line 10
> opt_a=
> # Use of uninitialized value.
> File 'PPC HD:Privat:MacPerl store:mini tests Ÿ:old:5-7'; Line 11
> opt_x=
Unfortunately in this case, Getopt::Std is very simple and only handles
options at the beginning of @ARGV. Your options are mixed in with regular
arguments.
However, you can do this with Getopt::Long, by setting the permute
configuration option. Here's a quick example:
#!/usr/local/bin/perl -w
use strict;
use Getopt::Long;
Getopt::Long::Configure('permute');
@ARGV = qw/ mbx2 5 -x tonus -a -x /;
use vars qw/ $opt_a @opt_x /;
GetOptions('a', 'x:s@');
print join('|', "$opt_a\n", @opt_x, "\n"), "@ARGV\n";
__END__
The call to GetOptions specifies an option named a, which takes no
arguments, and an option named s, which takes an optional string argument
and is returned as a list.
Getopt::Long also allows you to specify your own variables to put the
return values into, instead of $opt_a and so on.
Ronald