簡體   English   中英

如何使用perl使用命令行參數從目錄中獲取文件?

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


我試圖獲取具有文件夾名稱(即pro)和位置(即“ /c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt”)的文件並運行腳本(即p​​erl 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';

錯誤:

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

要運行命令行,如下所示:

我應該創建腳本來如下運行命令行。

perl readfile.pl -pro “pr1” -mfile “/c/lol/ap/a/ds/crent/stup/pjects/DEMO/mfile.txt” -odir “/home/html_files”

不確定您要在這里實現什么,但是您對GetOptions的使用是錯誤的。 如果您調用它,它將嘗試處理所有命令行選項,而不僅僅是一個。 因此,在第一次調用GetOption未定義的所有內容最終都會在末尾觸發or die ...部分並停止程序,從而產生用法消息。 查閱PerlDoc以獲得一些有用的示例。

您還必須在命令行調用中使用兩個連字符作為選項,以使其起作用...

調用GetOptions('pro' => \\$pro) -pro以外的所有其他選項視為無效,因此您必須在一個調用中處理所有可能的命令行選項

由於您的選項具有字符串值,因此您還需要在選項名稱后附加=s

看起來像這樣

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";

輸出

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