1. 程式人生 > >在Perl中使用Getopt::Long模組來接收使用者命令列引數

在Perl中使用Getopt::Long模組來接收使用者命令列引數

我們在linux常常用到一個程式需要加入引數,現在瞭解一下 perl 中的有關控制引數的模組 Getopt::Long ,比直接使用 @ARGV 的陣列強大多了.我想大家知道在 Linux 中有的引數有二種形式.

•長引數  –help
•短引數   -h
也就是-和–的分別.–表示完整引數.-表示簡化引數.在 Perl 的這個模組中也支援這二種方法.
這要介紹的二 Getopt 其實有二個模組,一個叫 Getopt::Long 一個叫 Getopt::Std.下面就只介紹 Getopt::Long 了.因為這個模組更加強大

Getopt::Long 模組
初始化 Perl命令列中所接受的引數,簡化了命令列引數的解析.下面看程式的例子

複製程式碼程式碼如下:
#!/usr/bin/perl 
use strict; 
use Getopt::Long; 
use Smart::Comments; 

my @libs    = ();  
my %flags   = ();  
my ( $verbose, $all, $more, $diam, $debug, $test, $step); 

GetOptions( 
        'verbose+'  => \$verbose, 
        'more!'     => \$more, 
        'debug:i'   => \$debug, 
        'lib=s'     => \@libs, 
        'flag=s'    => \%flags, 
        'test|t'    => \$test, 
        'all|everything|universe' => $all, 
); 

### $verbose 
### $more 
### $debug 
### $test 
### @libs; 
### %flags

這就是使用的方法,下面是詳細解釋,注意看 GetOptions 中的 => 前面的部分.下面是詳解

•‘verbose+'  接有 + 的選項不接收變數,後面不需要加內容.直接使用就行了,會在每次出現時增加一次變數,就是講命行時在引數中 -verbose -verbose 出現二次時 verbose 的值就會變成 2.
•‘more!'        接有 ! 的選項不接收變數(也就是講後面不需要加引數 –more 來使用就行了),只要命令列中出現了這個引數,就會預設是 1 ,是用來設定開啟和關掉一個功能的>.可以在引數前加 no 變成負的例如-nomore.
•‘flag=s'        接有 = 的字串要求接字串(s)、整數(i),或者浮點(f)等型別的變數.
•‘debug:i'      接有 : 的選項會接受預設為0或者為空字串的可選變數 
•‘test|t'          接有 | 的選項表示可以給 –test 簡寫為 -t.
•‘lib=s'     => @libs    如果相關聯的變數是個陣列, 如這個地方的 @libs, 那麼選項可以多次出現, 值可以被推到數組裡.
•‘flag=s'    => %flags  如果相關聯的變數是個雜湊, 那麼就要求一個鍵=值(key=value)對, 並被插入到雜湊裡.

備註:
     在匹配引數名的時候,GetOptions 在預設設定下會忽略大小寫,預設引數被簡寫為唯一的最短字串(首字母)(例如,-m 代表 -more. 相同的首字母時,會加上第二個字母來區分)

Getopt 模組的程式使用的方法:

根據上面的例子,比如我們寫了一個程式叫 test.pl .我們只需要在命令列中加如下引數:

複製程式碼程式碼如下: $ ./test.pl  --verbose --verbose -v --more \       --lib='/lib' -l '/lib64' --f a=1 --flag b=2  --debug 2 -t fukai

有點小長,在看看上面的,就會明白意思了.在這個地方,我使用了 Smart::Comment 模組,所以在最下面的 ###  是會輸出這個變數本身的內容的.這也是一個超級強大的模組.我們來看看輸入這些引數後.會輸出什麼內容吧.

複製程式碼程式碼如下:
### $verbose: 3 
### $more: 1 
### $debug: 2 
### @libs: [ 
###          '/lib', 
###          '/lib64' 
###        ] 
### %flags: { 
###           a => '1', 
###           b => '2' 
###         }

在對一下上面輸入的引數,明白了吧.

Getopt 模組的簡單總結

(1. 帶值引數傳入程式內部

※引數型別:整數, 浮點數, 字串

複製程式碼程式碼如下:
GetOptions( 
    'tag=s' => \$tag
); 

‘='表示此引數一定要有引數值, 若改用':'代替表示引數不一定要有引數值
‘s'表示傳遞字串引數, 若為'i'表傳遞整數引數, 若為'f'表傳遞浮點數.

帶值引數使用的方法

複製程式碼程式碼如下:
$ test.pl --tag=string 
$ test.pl --tag string 

(2. 需要傳送多個值的引數到程式中.

比如需要傳幾個值到 @libfiles 中的操作方法.

複製程式碼程式碼如下:
GetOptions ("library=s" => \@libfiles); 
GetOptions ("[email protected]" => \$libfiles); 

引數傳到 @$tag
使用的方法

複製程式碼程式碼如下: $ test.pl --library lib/stdlib --library lib/extlib

(3. 對鍵值對的引數傳遞

有時我們需要傳送一些鍵值對到程式中進行處理,就需要使用到這個功能了.

複製程式碼程式碼如下:
GetOptions ("define=s" => \%defines); 
GetOptions ("define=s%" => \$defines); 

使用的方法

複製程式碼程式碼如下: $ test.pl --define os=linux --define vendor=redhat

  (4. 引數的別名
我們需要引數加個簡寫之類的別名時,可以使用下面的方法

複製程式碼程式碼如下: GetOptions ('length|height=f' => \$length);

第一個名稱為 primary name, 其他的名稱為 alias(可有多個alias名稱) ,當使用hash引數時, 使用primary name作為key值

Storing options values in a hash:

Sometimes, for example when there are a lot of options, having a separate variable for each of them can be cumbersome. GetOptions() supports, as an alternative mechanism, storing options values in a hash.To obtain this, a reference to a hash must be passed as the first argument to GetOptions(). For each option that is specified on the command line, the option value will be stored in the hash with the option name as key. Options that are not actually used on the command line will not be put in the hash, on other words, exists($h{option}) (or defined()) can be used to test if an option was used. The drawback is that warnings will be issued if the program runs under use strict and uses $h{option} without testing with exists() or defined() first。

my %h = ();
GetOptions (\%h, 'length=i');# will store in $h{length}

For options that take list or hash values, it is necessary to indicate this by appending an @ or % sign after the type:
GetOptions (\%h, '[email protected]');# will push to @{$h{colours}}
To make things more complicated, the hash may contain references to the actual destinations, for example:
my $len = 0;
my %h = ('length' => \$len);
GetOptions (\%h, 'length=i');# will store in $len

This example is fully equivalent with:
my $len = 0;
GetOptions ('length=i' => \$len);# will store in $len

Any mixture is possible. For example, the most frequently used options could be stored in variables while all other options get stored in the hash:
my $verbose = 0;# frequently referred
my $debug = 0;# frequently referred
my %h = ('verbose' => \$verbose, 'debug' => \$debug);
GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
if ( $verbose ) { ... }
if ( exists $h{filter} ) { ... option 'filter' was specified ... }

相關推薦

Perl使用Getopt::Long模組接收使用者命令引數

我們在linux常常用到一個程式需要加入引數,現在瞭解一下 perl 中的有關控制引數的模組 Getopt::Long ,比直接使用 @ARGV 的陣列強大多了.我想大家知道在 Linux 中有的引數有二種形式. •長引數  –help •短引數   -h 也就是-和–的分別.–表示完整引數.-表示簡化

Perl 使用 Getopt::Long 模組接收使用者命令引數 z

初始化 Perl命令列中所接受的引數,簡化了命令列引數的解析。下面看程式的例子 #!/usr/bin/perl use strict; use Getopt::Long; use Smart::Comments; my @libs    = (); my %flags   = (); my ( $verbos

php在cli模式下取得命令引數的方法-getopt命令可傳遞陣列-簡單自定義方法取命令引數

  在cli模式下執行PHP時,自動給指令碼檔案傳遞了一個變數$argv,其值即是一個命令中所有值組成的陣列(以空格區分),在PHP程式中接收引數有3種方法1.直接使用argv變數陣列。 2.使用$_SERVER['argv']全域性變數來獲取,其值和1是一樣的。 3.使用getopt

[Python小筆記]命令引數:sys.argv和getopt模組

一、sys.argv sys.argv 是命令列引數列表。 #test_sys_argv.py import sys print(sys.argv)#命令列引數列表 print(sys.argv[0]) print(len(sys.argv))#命令列引數列表個數 二、g

python處理命令引數模組optpars

optpars是python中用來處理命令列引數的模組,可以自動生成程式的幫助資訊,功能強大,易於使用,可以方便的生成標準的,符合Unix/Posix 規範的命令列說明。使用 add_option() 來加入選項,使用 parse_args() 來解析命令列。add_opti

PerlFile::Find模組的一個經典用法

     find通常被用來查詢特定路徑下的特定檔案,用來搜尋檔名非常有用,是perl中使用非常廣泛的檔案操作函式。      先看個例子: use File::Find; find(\&PrintName, @curDir); su

GDI+實現的圖片相互轉換程式,可以通過命令引數呼叫

#include <gdiplus.h> #include <stdio.h> using namespace Gdiplus; #include "stdafx.h" #pragma comment(lib, "gdiplus.lib") //探測PNG編碼器的

在android通過java層程式呼叫命令的一些備註

能呼叫哪些命令? 一般性的, 最常用的命令都能呼叫, 比如cat, cp, top, ls, ps命令, 但用法和linux上的有較大區別, 可通過–help/-h查詢具體的命令用法; 我熟知linux terminal命令列, 但如何知道android都有哪些常用命令呢? 首

shell 從檔案讀取批量檔名並做命令操作

222檔案內容: /home/zhangsuosheng/Desktop/9-30/9_30/1bak/1538291162.png /home/zhangsuosheng/Desktop/9-30/9_30/1bak/1538291212.png /home/zhangsuosheng/Deskto

Java的輸入和輸出、if...else if...else判斷、Java列印陣列、Java陣列排序、檢視函式方法的原始碼、命令引數

Java的輸入和輸出: 輸入: import java.util.Scanner Scanner s = new Scanner(System.in); //通過new Scanner(System.in)建立一個Scanner物件,控制檯會一直等待輸入,直到敲回車鍵

【舊文章搬運】獲取並修改PEB的映像路徑,命令和當前目錄

原文發表於百度空間,2008-7-24 當時對UNICODE_STRING的使用還有點問題,導致最終效果圖中字串被截斷了========================================================================== 先從分析PEB開始吧.感覺分析這個東

Spring boot 梳理 - 在bean使用命令引數-自動裝配ApplicationArguments

If you need to access the application arguments that were passed to SpringApplication.run(…​), you can inject a org.springframework.boot.ApplicationArgumen

編寫一個程式,實現從命令引數輸入一字串,統計該字串字元輸入字元的出現的次數。

package pro1214test; import java.util.Scanner; public class eCiShu { public static void main(String[] args) { Scanner s = new Scanner(System.

pycharm傳入命令引數

參考網址: 設定的地方: Run/Debug Configurations->Configurations->Script Parames 和vs類似,都不用輸入程式名字,直接輸入引數即可。 如,在命令列中需要輸入 python a.py b c d 則在上述地方直接輸入 b c d就行了

python 命令引數——argparse模組的使用

以下內容主要來自:http://wiki.jikexueyuan.com/project/explore-python/Standard-Modules/argparse.html argparse 使用 簡單示例 我們先來看一個簡單示例。主要有三個步驟: 建立 ArgumentParser(

控制檯解析使用者輸入的命令引數(argc argv)

命令列解析:argc argv  解析例子: tail -hlocalhost -p8002 -l200或 tail -hlocalhost -p 8002 -l 200 *.h: #include <unistd.h> #define COMMAND_LINE_LENGTH 204

修改MakefileCROSS_COMPILE報錯,但是命令指定CROSS_COMPILE引數卻正常

編譯linux核心,修改Makefile中CROSS_COMPILE報錯,但是命令列中指定CROSS_COMPILE引數卻可以正常編譯! 解決方法:在Makefile中指定CROSS_COMPILE為絕對路徑,全路徑!

python命令引數處理:argparse、optparse和getopt

一 命令列引數: (1)在python中: *sys.argv:命令列引數的列表。 *len(sys.argv):命令列引數的個數(argc)。 *python中提供了三個模組來輔助處理命令列引數:getopt,optparse和argparse。 (2)術語: *arg

Python命令引數解析模組argparse

當寫一個Python指令碼時經常會遇到不同引數不同功能的情況,如何做一個更好看的命令幫助資訊以及對命令引數解析呢? 這就需要使用argparse模組 #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os impor

getopt(win32) -- 命令引數解析函式

GNU libc提供了getopt和getopt_long用於解析命令列引數,很好用,想在windows下使用,就google了幾個win32下的C/C++寫得getopt,並作了一些比較。 程式裡往往會有許多開關的,執行時就要傳入許多引數值來開啟或關閉這些開關。以前