Search code examples
perlgetopt

Script does not die if there are incorrect arguments


I'm quite new to the Perl programming. I want to use GetOptions to parse input arguments for my script. I have simple problem - I want script to exit with usage message if there's mess in arguments or arguments are missing values (for mandatory arguments). src_xml is mandatory argument but if I run the script not providing value for this argument, I get an error message about usage of uninitialized value $src_xml in -e at tenant_tenant.pl. What am I doing wrong? Or do I have to check every variable if its defined?

my $dev;
my $src_xml;
my $tgt_syscd = 'L86'; 
my $tgt_path = '/tmp/test/exports'; 
my $help;

GetOptions('src_xml=s' => \$src_xml,
        'tgt_syscd=s' => \$tgt_syscd,
        'tgt_path=s' => \$tgt_path,
        'dev' => \$dev,
        'h|help' => \$help
) or die "Usage: perl $0 --src_xml NAME --tgt_syscd NAME  --tgt_path NAME 
\n";

#checking for help
if ( defined $help ) {
    die $help_message;
}

Solution

  • Your script will die only this way:

    perl ./foo.pl --src_xml=

    Check arguments with custom subroutine?

    GetOptions(
        'dec-to-base35=i' => \&dec_to_base35,
        'base35-to-dec=s' => \&base35_to_dec,
    );
    
    sub dec_to_base35 ( $opt_name, $decimal_value ) {
    ...
    

    Complete example here

    BTW, you can join "Perl weekly challenge", this may help to learn something new