Perl @ARGV 獲取命令參數


# temp.pl
use strict;
use warnings;
use Data::Dumper qw(Dumper);
 
print Dumper \@ARGV;

執行上面的代碼,打印:

$ perl temp.pl -a=1 -b=2 -c
$VAR1 = [
          '-a=1',
          '-b=2',
          '-c'
        ];

腳本名為“$0”與“FILE”類似

print "$0 \n";
print __FILE__ . "\n"

$ perl temp.pl -a=1 -b=2 -c
temp.pl
temp.pl

從@ARGV提取命令行參數

可以使用常規數組操作符來獲取參數

my $name   = $ARGV[0];
my $number = $ARGV[1];

my ($name, $number) = @ARGV;

my $name = shift @ARGV;

檢查參數

my ($name) = @ARGV;

if(!defined($name)){
  die "need name.\n";
}

# 簡寫
my $name = $ARGV[0] // die "need name. \n";

# or set defualt value

my ($name) = @ARGV;
$name = $name // 'default';
print "$name \n";

使用“Getopt::Long”解析參數

#!/usr/bin/perl

use strict;
use utf8;
use autodie;
use warnings;
use Encode qw(decode encode);
use Data::Dumper qw(Dumper);
use Getopt::Long qw(GetOptions);

my $name   = "ajanuw";
my $age = 0;

GetOptions ("name=s" => \$name,    # string
            "age=i"   => \$age)      # string
or die("Error in command line arguments\n");

print "$name - $age \n";

執行上面的腳本:

$ perl temp.pl --name=Ajanuw --age=12 
Ajanuw - 12 

或則其它方式

--age 12
-age 12
-age=12

-a 12

無值參數

my $help;
GetOptions ("help" => \$help) or die("Error in command line arguments\n");
  print "... \n" if(defined($help));

$ perl temp.pl --help
... 

數組參數

my @arr;
GetOptions ("arr=s" => \@arr) or die("Error in command line arguments\n");
print Dumper @arr;

$ perl temp.pl -a=a -a=b
$VAR1 = 'a';
$VAR2 = 'b';

hash參數

my %hash;
GetOptions ("hash=s" => \%hash) or die("Error in command line arguments\n");
print %hash;

$ perl temp.pl --hash name=ajanuw --hash age=12
age12nameajanuw

GetOptions函數僅在相關時才處理以短划線開頭的參數及其對應的值。處理完選項后,會將其從@ARGV中刪除。(選項名稱和選項值都將被刪除。)命令行上的其他任何非關聯值都將保留在@ARGV中。

use Data::Dumper qw(Dumper);
use Getopt::Long qw(GetOptions);

my $name;
GetOptions ("name=s" => \$name) or die("Error in command line arguments\n");
print "$name \n" if(defined($name));
print Dumper \@ARGV;


$ perl temp.pl -n Ajanuw a.txt b.txt
Ajanuw 
$VAR1 = [
          'a.txt',
          'b.txt'
        ];

處理完選項后,將a.txt和b.txt保留在@ARGV中。現在,我們可以對它們執行任何操作,例如,可以使用foreach遍歷@ARGV數組。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM