in reply to Requiring option values in Getopt::Long

I re-read the documentation again and figured out that this code actually solves what I want.
#!/usr/bin/perl use warnings; use strict; use Getopt::Long; my ($option_test); my $check_option = GetOptions( "test=s" => \$option_test ); die 'Invalid option' if ( $check_option ne 1 ); print "next line";
Here's the result when I ran some tests.
$ test.pl next line $ test.pl -t abc next line $ test.pl -t Option test requires an argument Invalid option at test.pl line 9.
Thank you all for your help.

Replies are listed 'Best First'.
Re^2: Requiring option values in Getopt::Long
by ikegami (Patriarch) on Aug 20, 2009 at 03:27 UTC

    Why the redundant error error message? A cleaner version was previously suggested to you.

    GetOptions( 'test=s' => \$option_test ) or exit(1); defined($option_test) or die("Missing argument -t");

    At the very least, remove the line number from the error message. It's useless clutter.

    GetOptions( 'test=s' => \$option_test ) or die("Invalid command-line option\n"); defined($option_test) or die("Missing argument -t\nInvalid command-line option\n");

    However, I suggest that you display a useful error message instead:

    use File::Basename qw( basename ); sub help { my $prog = basename($0); print("usage: $prog -t [options]\n"); exit(0); } sub usage { my $msg = shift || ''; my $prog = basename($0); die("${msg}Use $prog --help for help\n"); } GetOptions( 'help|h|?' => \&help, 'test=s' => \$option_test, ) or usage(); defined($option_test) or usage("Missing argument -t\n");

      I usually prefer to write documentation for script as POD and then use Pod::Usage to show help message.