如何在Perl中使用命令行參數從用戶輸入文件?可能是這樣的:wxp.pl - file {file path}
。
我是Perl中的新成員,所以向我推薦任何有用的東西。我怎麼能讓它像命令行中提出的多於一個參數一樣。 例如:perl中使用argV的多個命令行輸入
exp.pl -file {file path}
-x {it's arg}
-y {y's arg}
如何在Perl中使用命令行參數從用戶輸入文件?可能是這樣的:wxp.pl - file {file path}
。
我是Perl中的新成員,所以向我推薦任何有用的東西。我怎麼能讓它像命令行中提出的多於一個參數一樣。 例如:perl中使用argV的多個命令行輸入
exp.pl -file {file path}
-x {it's arg}
-y {y's arg}
我會建議GetOpt :: Long來實現這一點。但是,如果你想使你自己看看是否像這樣將方便:
use strict;
use warnings;
# Usage check. For "perl xxx.pl -a arg1 -b arg2" args. should be even nos.
if (scalar @ARGV == 0 or scalar @ARGV % 2 != 0) {
print "Usage:\n\t$0 -a arg1 -b arg2 requires all args\n";
exit 0;
}
# This one convert cmd line args. to hash ex. (perl xxx.pl -a arg1 -b arg2) to {-a => arg1, -b => arg2}
my %argHash = @ARGV;
# Optional but see if all the args are present
my $maxArgs = 2;
if (scalar keys %argHash != $maxArgs) {
print "Usage:\n\t$0 -a arg1 -b arg2 requires exactly $maxArgs args\n";
exit 0;
}
# Parse arguments.
print "$0:\n";
for my $key (keys %argHash) {
print "\t $key: $argHash{$key}\n";
}
1;
結果:
c:\swadhi\perl>perl cmdline.pl
Usage:
cmdline.pl -a arg1 -b arg2 requires all args
c:\swadhi\perl>perl cmdline.pl -a "user" -b
Usage:
cmdline.pl -a arg1 -b arg2 requires all args
c:\swadhi\perl>perl cmdline.pl -a "user" -b "Command"
cmdline.pl:
-a: user
-b: Command
c:\swadhi\perl>perl cmdline.pl -a "user" -b "Command" -c "mock"
Usage:
cmdline.pl -a arg1 -b arg2 requires exactly 2 args
c:\swadhi\perl>perl cmdline.pl -a "user"
Usage:
cmdline.pl -a arg1 -b arg2 requires exactly 2 args
更簡單的getopt ::龍版
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
my $user_name;
GetOptions('user=s' => \$user_name) or die "Usage: $0 --user NAME\n";
if ($user_name) {
print $user_name, "\n";
}
結果:
c:\swadhi\perl>perl cmdline.pl -user Swadhi
Swadhi
c:\swadhi\perl>perl cmdline.pl
c:\swadhi\perl>perl cmdline.pl -p s
Unknown option: p
Usage: cmdline.pl --user NAME
c:\swadhi\perl>perl cmdline.pl -u "This should also work"
This should also work
好吧,我會嘗試在我的解決方案中使用這一個,謝謝。雖然我正在一個電子郵件模塊中,我想輸入一個電子郵件ID作爲參數,所以它會發送郵件給這些ID並且我正在使用mail :: outlook。 –
當然。我會建議你練習它以獲得更全面的理解,並以非常簡單的例子將其留下。歡呼! :) –
Ohhk謝謝,我得看看** Getopt :: Long **因爲我不知道如何做到這一點你進入perl你知道。 –
只需看一看,然後嘗試從自己那裏得到答案,如果遇到任何問題,請隨身攜帶。我們很樂意幫助您。 – serenesat
同意!謝謝安詳.. –