简体   繁体   中英

How to get the file from the directory using command line arguments using perl?


I tried to fetch the file with folder name(ie pro) and location(ie “/c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt) and run the script(ie 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”

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...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM