在perl脚本中使用传入的变量

Sam*_*Sam 1 perl file-handling

我想做点什么

for i in (1..100)
do
     ./perlScript.pl
done
Run Code Online (Sandbox Code Playgroud)

其中perlScript.pl将打开一个文件句柄

#!/usr/bin/perl -w
use strict;
my $file = 'info${i}.txt';
my @lines = do {
    open my $fh, '<', $file or die "Can't open $file -- $!";
    <$fh>;
};
Run Code Online (Sandbox Code Playgroud)

我想要一些如何从脚本中访问该字母的建议.即使我可以将txt文件作为参数传入,然后像$ 1或其他东西一样访问它

谢谢

xxf*_*xxx 5

您可以将命令行参数传递给perl,它们将显示在特殊数组中@ARGV.

基本命令行参数传递

# In bash
./perlScript.pl 123

# In perl
my ($num) = $ARGV[0];  # The first command-line parameter [ 123 ]
Run Code Online (Sandbox Code Playgroud)

许多位置命令行参数

# In bash
./perlScript.pl 123 456 789 foo bar

# In perl
my ($n1,$n2,$n3,$str1,$str2) = @ARGV;  # First 5 command line arguments will be captured into variables
Run Code Online (Sandbox Code Playgroud)

许多命令行标志

# In bash
./perlScript.pl --min=123 --mid=456 --max=789 --infile=foo --outfile=bar

# In perl
use Getopt::Long;

my ($min,$mid,$max,$infile,$outfile,$verbose);
GetOptions(
    "min=i"     => \$min,     # numeric
    "mid=i"     => \$mid,     # numeric
    "max=i"     => \$mix,     # numeric
    "infile=s"  => \$infile,  # string
    "outfile=s" => \$outfile, # string
    "verbose"   => \$verbose, # flag
) or die("Error in command line arguments\n");
Run Code Online (Sandbox Code Playgroud)

环境变量

# In bash
FOO=123 BAR=456 ./perlScript.pl 789

# In perl
my ($foo) = $ENV{ FOO } || 0;
my ($bar) = $ENV{ BAR } || 0;

my ($baz) = $ARGV[0]    || 0;
Run Code Online (Sandbox Code Playgroud)

perldoc perlvar - 关于@ARGV和的详细信息%ENV

perldoc Getopt :: Long