user1801060
user1801060

Reputation: 2821

Parse single switch only, raise ignore the rest or raise an error message

I'm a Perl newbie. I'm writing a script that will read only one argument. It will call a usage function if anything other than the specified params are put in.

When I use getopt(), the script does'nt output anything. If I use getopts(), it processses all my arguments. What am I doing wrong?

use strict; 
use warnings;
use Getopt::Std;

sub main
{
    my %opts;   

    getopt('abcd', \%opts) or usage();

    if($opts{c}) {
        print "Got -c flag\n";
    }

    if($opts{a}) {
        print "Got -a flag\n";
    }

    if($opts{b}) {
        print "Got -b flag\n";
    }   
}

sub usage
{
    printf("There is an error in your options, try %s", $0);
}

main();

Upvotes: 2

Views: 66

Answers (1)

Dave Sherohman
Dave Sherohman

Reputation: 46207

You're not doing anything wrong. You need to use getopts(), so that you'll get all specified options, and then throw an error if there's more than one present:

getopts('abcd', \%opts) or usage();
usage() if scalar keys %opts != 1;

Upvotes: 3

Related Questions