0

I tried to fetch the file with folder name(i.e pro) and location(i.e “/c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt) and run the script(i.e perl readfile.pl) using command line arguments.So i tried for the following sample script by my own.But i feel my script is totally wrong.Could anyone help me the right way to approach.

Sample Script:(perl readfile.pl)

use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $pro;
my $mfile;
my $odir;
GetOptions('pro' => \$pro) or die "Usage: $0 --pro\n";
GetOptions('mfile' =>\$mfile) or die "Usage:$0 --mfile\n";
GetOptions('odir' =>\$odir) or die "Usage:$0 --odir\n";
print $pro ? 'pro' : 'no pro';

Error:

Unknown option: mfile
Unknown option: odir
Usage: readfile.pl --pro

To run command line as follows :

I should create the script to run the command line as follows.

perl readfile.pl -pro “pr1” -mfile “/c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt” -odir “/home/html_files”
1
  • What is the objective of the script? To print the contents of a file passed via arguments? Commented Feb 16, 2017 at 13:16

2 Answers 2

1

The call GetOptions('pro' => \$pro) sees all options other than -pro as invalid, so you must process all possible command line options in a single call

Since your options have a string value, you also need to append =s to the option name

It would look like this

use strict;
use warnings 'all';

use Getopt::Long 'GetOptions';

GetOptions(
    'pro=s'   => \my $pro,
    'mfile=s' => \my $mfile,
    'odir=s'  => \my $odir,
);

print $pro   ? "pro   = $pro\n"   : "no pro\n";
print $mfile ? "mfile = $mfile\n" : "no mfile\n";
print $odir  ? "odir  = $odir\n"  : "no odir\n";

output

pro   = pr1
mfile = /c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt
odir  = /home/html_files
Sign up to request clarification or add additional context in comments.

1 Comment

It helps my query.Great explanation@Borodin
1

Not sure what you're trying to achieve here, but your usage of GetOptions is wrong. If you call it, this tries to process all commandline options, not just one. So everything not defined in your first call to GetOption ends up triggering the or die ... part at the end and stops the program, resulting in the usage message. Please look up PerlDoc for some useful examples.

You also have to use two hyphens for your options in the commandline call to let it work...

1 Comment

"You also have to use two hyphens for your options in the commandline call to let it work" No, you don't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.