mandog has asked for the wisdom of the Perl Monks concerning the following question:

I've gotten in the habit of creating error messages like this:

use strict ; use Getopt::Long; my ($username,$password,$group); my $err_msg=''; GetOptions('u=s' => \$username,'g=s'=> \$group, 'p=s'=>\$password); $err_msg.="missing -u username\n" unless $username; $err_msg.="missing -g group\n" unless $group; $err_msg.="missing -p password\n" unless $password; die "$err_msg" if $err_msg;

It works without obvious errors, but somehow this feels wrong...

Am I missing something...



email: mandog

Replies are listed 'Best First'.
Re: .= $err_msg
by particle (Vicar) on Apr 27, 2002 at 03:18 UTC
    i'd do something like:
    #!/usr/bin/perl -w use strict; use Getopt::Long; my( $username, $password, $group ); my %params = ( 'u=s' => \$username, 'p=s' => \$password, 'g=s' => \$group, ); sub usage { die << "USAGE"; Usage: $0 -u username -p password -g group [-others] Description: whatever... USAGE } usage() unless( GetOptions( %params ) ); for( values %params ) { usage() unless defined ${ $_ }; }
    • this captures the return code from GetOptions (please do this!)
    • i tend not to customize usage information (one doc for everyone, and they should read it!)
    • there's no $err_msg variable in file scope for the rest of the program (remember to use undef when you're done with it)

    ~Particle *accelerates*

      That last loop just begs for trimming:

      grep { not defined $$_ } values %params or die usage();

      Well, maybe it's just me. But I really think that judicious grep usage is much clearer than equivalent for loops.

          -- Chip Salzenberg, Free-Floating Agent of Chaos

Re: .= $err_msg
by BUU (Prior) on Apr 27, 2002 at 02:11 UTC
    I might prefer doing it with a loop and pushing all the new error messages onto an 'error' array, but thats personal taste.