LPM: getopts *elp
Rich Bowen
rbowen at rcbowen.com
Wed Aug 16 06:34:01 CDT 2000
Apparently Ken sent this from the wrong address.
Frank Price wrote:
>
> > ----------
> > From: Frank Price[SMTP:FPRICE at MIS.NET]
> > Sent: Tuesday, August 15, 2000 6:15:55 PM
> > To: lexington-pm-list at happyfunball.pm.org
> > Subject: LPM: getopts *elp
> > Auto forwarded by a Rule
> >
> Hi LexPM,
>
> I'm trying to use Getopt::Std and it isn't working as I'd like.
> Thought I'd post here before digging deeper :-)
>
> I want to use an option, -s, which takes an optional argument. If the
> argument is given, I want to use that argument. If just the option is
> given, I want to use a default value. If the option isn't given, I
> don't want to use any value at all. For example, you could say '-s
> 100', '-s', or omit it entirely.
>
> Here's what I thought would work. It doesn't though: if I don't
> specify the argument, $opt{'s'} is set to zero.
>
> use Getopt::Std;
>
> getopts('s:', \%opt);
> my $sleep = 0;
>
> if ($opt{'s'}) {
> print "opt_s = $opt{'s'}\n";
> $sleep = ($opt{'s'} == 1) ? 3600 : $opt{'s'};
> }
>
> print "sleep = $sleep\n";
>
> I think Getopt::Long will really do optional numeric args like I want
> -- anyone know if I can do this with Std options?
>
I don't know Getopt::Std, but I think I can get you what you want.
You can scrap the comments later, of course.
================
use Getopt::Std;
# I assume the colon is syntax Getopt::Std uses
getopts('s:', \%opt);
my $sleep = 0;
# Define the default value before getting to the
# next statements.
$default_s = 100;
# "exists" prevents giving $opt{s} a value if it is undefined;
# autovivifying can clobber you here!
if exists ($opt{s}) {
# This puts in a default value when "s" is a key, but its
# value is undef.
$opt{s} = $default_s unless defined($opt{s});
}
==================
Hope that helps.
-- Ken
More information about the Lexington-pm
mailing list