0

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?

toolic
  • 57,801
  • 17
  • 75
  • 117
vkk05
  • 3,137
  • 11
  • 25
  • 1
    The check and call of `HelpMessage` is according to your code done after the print and after the execution of `doSomeOperation` and after the printing of `END`. You have to put this check directly after the call of `GetOptions`. – Steffen Ullrich Sep 14 '20 at 18:42
  • @SteffenUllrich Oh ya. You're right. Thank you for the correction. – vkk05 Sep 14 '20 at 18:44

1 Answers1

2

Your check comes too late.

doSomeOpearation($node, $command);

...

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

should be

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

doSomeOpearation($node, $command);

...
ikegami
  • 367,544
  • 15
  • 269
  • 518