2010-10-19 168 views
3

我想分析的Perl腳本的參數列表,例如我有這種情況:如何解析命令行參數?

script.pl -h 127.0.0.1 -u user -p pass arg1 arg2 arg3 

我如何可以解析不在陣列選項參數列表做,和標量值中的選項參數?

謝謝。

+3

在_Mastering Perl_中,我介紹了90多個Perl模塊,它們可以讓您以任何喜歡的方式執行此操作。 :) – 2010-10-19 22:23:37

回答

10

那麼,如果它們是命令行中唯一沒有作爲選項給出的東西,那麼它們應該仍然在@ARGV。所以只需使用@ARGV

use Getopt::Long; 

# save arguments following -h or --host in the scalar $host 
# the '=s' means that an argument follows the option 
# they can follow by a space or '=' (--host=127.0.0.1) 
GetOptions('host=s' => \my $host 
      , 'user=s' => \my $user # same for --user or -u 
      , 'pass=s' => \my $pass # same for --pass or -p 
     ); 

# @ARGV: [ qw<arg1 arg2 arg3> ] 

看到Getopt::Long

12

你的程序的參數都存儲在@ARGV

如果您想要對交換機進行任何處理,請使用Getopt::Long,這是一個標準的Perl模塊。

即使你認爲「哦,我可以從列表中挑選我想要的東西」,請使用Getopt::Long,因爲我保證你會增加更多開關的時間到了,你會說話「男人,我希望我從一開始就開始使用Getopt :: Long。」

請同時參閱我的博客文章"Use Getopt::Long even if you think you don't need it"