【问题标题】:How to pass directory path as arguments from command line using perl?如何使用 perl 从命令行将目录路径作为参数传递?
【发布时间】:2017-03-06 13:01:16
【问题描述】:

我的问题如下:

我对如何传递命令行参数而不是使用 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 中的内容。所以我需要在变量内传递命令行参数(即$location_dir)而不是直接传递路径我该怎么做?

【问题讨论】:

    标签: perl


    【解决方案1】:
    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");
    

    【讨论】:

    • 你能解释一下你为什么使用帮助选项@ikegami
    • 没必要。但我觉得这比将print(STDERR "Ask user "find data" on StackOverflow for usage\n"); 放入usage() 更好:)
    猜你喜欢
    • 2013-06-03
    • 2016-08-11
    • 2011-04-20
    • 2012-11-23
    • 2013-12-07
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多