我的问题如下:
我想知道如何传递命令行参数而不是使用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.so中的内容我需要在变量内传递命令行参数(即$location_dir
)而不是直接传递路径我该怎么办?
答案 0 :(得分: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");