Search code examples
perlcommand-line-argumentsgetopt-long

Exit from the script if required arguments not found in Perl


I have script which should take two arguments from command line. To achieve that, I am using Getopt::Long Perl module.

Here is the script:

#!/usr/bin/perl

use strict;
use warnings;

use Getopt::Long 'HelpMessage';

GetOptions(
  'node|n=s' => \my $node,
  'cmd|c=s'  => \my $command,
  'help'     =>  sub { HelpMessage(0) }
) or HelpMessage(1);

print "Node:$node\nCmd:$command\n";

doSomeOpearation($node, $command);

print "END\n";

sub doSomeOpearation {
    my ($n, $c) = @_;
    #...
    return;
}

HelpMessage(1) unless ($node && $command);

=head1 NAME

run_command - Run Commands on SVC Server

=head1 SYNOPSIS

  --node,-n       Node name (required)
  --command,-c    Command (required)
  --help,-h       Print this help

=head1 VERSION

1.00

=cut

The script works fine in positive scenario, i.e., if I pass 2 arguments to the script its printing those arguments in the screen.

But, if I pass only one argument the script, it should go to HelpMessage function. Instead of that here script gives me Use of uninitialized value $command in concatenation (.) or string at script2.pl line 14. warning and prints END message too.

How can I print HelpMessage and exit from the script unless there are 2 arguments?


Solution

  • Your check comes too late.

    doSomeOpearation($node, $command);
    
    ...
    
    HelpMessage(1) unless ($node && $command);
    

    should be

    HelpMessage(1) unless ($node && $command);
    
    doSomeOpearation($node, $command);
    
    ...