in reply to Getopts::Long -- changing its behavior

You don't mention how you initialize Getopt::Long, but you should be able to define 'file' as a boolean switch rather than a value field. Running the following:

#!/usr/bin/perl use strict; use Getopt::Long; my ( $file, $name ); GetOptions( file => \$file, name => \$name ); print "File: $file\nName: $name\n";

with:

perl test_getopt.pl -file -name

produces:

File: 1 Name: 1

which sounds like what you want.

Chris
M-x auto-bs-mode

Replies are listed 'Best First'.
Re: Re: Getopts::Long -- changing its behavior
by jonjacobmoon (Pilgrim) on Feb 06, 2002 at 04:53 UTC
    Nope. What I want is to be able to do:

    myscript.pl -file -name

    And get the error that -file requires a string. In the case here, I don't get the error. I get file set to "-name". In other words, I want getopts to recognize that a switch has followed the one I wanted to take a string instead of a string as a required, so the user does not need to worry about what order s/he puts the switch in.


    I admit it, I am Paco.
      Something like this might do what you need:
      GetOptions(\%param, 'file:s', 'name:s', 'any:s', 'other:s', 'params:s' +); foreach (qw(file name any other params)) { die "Option $_ requires an argument\n" if defined($param{$_}) && $pa +ram{$_} eq ''; }

      Using the colon (e.g. 'file:s') in the GetOptions call instead of an equals sign makes a string parameter on the switch optional rather than required. As a result, when GetOptions sees '-file -name', it interprets this as 'switch -file with no optional string param, followed by switch -name with no optional string param', rather than as 'switch -file with string param -name'. Then the subsequent loop goes through and complains if one of those "optional" parameters in fact has an empty value.

      Also, if you check the perldoc for Getopt::Long you'll find that you can define handler subroutines to be called when an individual switch is encountered, which would probably also let you trap the case that's bothering you. I haven't used that capability in a while and it seems like it would be more work, but perhaps I haven't addressed all the angles of your question.

      Good luck!

        Thanks for the response, but again. Nope. Your answer is similiar to what I came up with, but what I was looking for is a configuration option that requires no extra written code. I just can't understand why getopts allows this. Kind of a pain.


        I admit it, I am Paco.