简体   繁体   English

如何使用perl使用命令行参数从目录中获取文件?

[英]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. 我试图获取具有文件夹名称(即pro)和位置(即“ /c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt”)的文件并运行脚本(即p​​erl readfile)。 pl)使用命令行参数。所以我自己尝试了以下示例脚本。但是我觉得我的脚本是完全错误的,谁能帮助我找到正确的方法。

Sample Script:(perl readfile.pl) 示例脚本:(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. 不确定您要在这里实现什么,但是您对GetOptions的使用是错误的。 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. 因此,在第一次调用GetOption未定义的所有内容最终都会在末尾触发or die ...部分并停止程序,从而产生用法消息。 Please look up PerlDoc for some useful examples. 查阅PerlDoc以获得一些有用的示例。

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 调用GetOptions('pro' => \\$pro) -pro以外的所有其他选项视为无效,因此您必须在一个调用中处理所有可能的命令行选项

Since your options have a string value, you also need to append =s to the option name 由于您的选项具有字符串值,因此您还需要在选项名称后附加=s

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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