簡體   English   中英

如何使用perl從命令行傳遞目錄路徑作為參數?

[英]How to pass directory path as arguments from command line using perl?


我的問題如下:

我很想知道如何傳遞命令行參數,而不是使用perl傳遞目錄路徑。

示例假定是否按以下方式執行文件:

./welcome.pl -output_dir "/home/data/output" 

我的代碼:

#!/usr/local/bin/perl
use strict;
use warnings 'all';
use Getopt::Long 'GetOptions';
GetOptions(
          'output=s'  => \my $output_dir,

); 
my $location_dir="/home/data/output";
print $location_dir;

代碼說明:

我試圖在$ output_dir.print中打印內容,所以我需要傳遞變量內的命令行參數(即$location_dir ),而不是直接傳遞路徑,我該怎么辦?

use strict;
use warnings 'all';

use File::Basename qw( basename );
use Getopt::Long   qw( GetOptions );

sub usage {
   if (@_) {
      my ($msg) = @_;
      chomp($msg);
      print(STDERR "$msg\n");
   }

   my $prog = basename($0);
   print(STDERR "$prog --help for usage\n");
   exit(1);
}

sub help {
   my $prog = basename($0);
   print(STDERR "$prog [options] --output output_dir\n");
   print(STDERR "$prog --help\n");
   exit(0);
}

Getopt::Long::Configure(qw( posix_default ));  # Optional, but makes the argument-handling consistent with other programs.
GetOptions(
    'help|h|?' => \&help,
    'output=s' => \my $location_dir,
)
    or usage();

defined($location_dir)
    or usage("--output option is required\n");

print("$location_dir\n");

或者,當然,如果確實需要該參數,那么為什么不只使用./welcome.pl "/home/data/output"而不是一個不是真的可選參數。

use strict;
use warnings 'all';

use File::Basename qw( basename );
use Getopt::Long   qw( GetOptions );

sub usage {
   if (@_) {
      my ($msg) = @_;
      chomp($msg);
      print(STDERR "$msg\n");
   }

   my $prog = basename($0);
   print(STDERR "$prog --help for usage\n");
   exit(1);
}

sub help {
   my $prog = basename($0);
   print(STDERR "$prog [options] [--] output_dir\n");
   print(STDERR "$prog --help\n");
   exit(0);
}

Getopt::Long::Configure(qw( posix_default ));  # Optional, but makes the argument-handling consistent with other programs.
GetOptions(
    'help|h|?' => \&help,
)
    or usage();

@ARGV == 1
    or usage("Incorrect number of arguments\n");

my ($location_dir) = @ARGV;

print("$location_dir\n");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM