3

我在分配参数值/命令行参数时遇到了麻烦。这是我真正想做的。

Test.pl
#!/usr/bin/perl

#Variable declaration

$RUN_DIR="/home/ckhau/database/experiment/test";
    #Main program

$index=-999; 
#my $ARGV;
@files = <$RUN_DIR/b*.txt>;

foreach $file (@files)
{
 #$SCRIPT="perl abcdinfo.pl $file";
 $SCRIPT="perl abc.pl $file";
 system("$SCRIPT");       
}

我尝试用 @ARGV 替换 b*.txt 并尝试运行程序,即当我将上面的代码替换为

@files = <$RUN_DIR/@ARGV>;

然后尝试使用命令行运行

perl Test.pl b*.txt

这给了我一个错误 perl: no match。任何人都可以在以下方面帮助我。

如何为此使用命令行参数???

我可以在命令行“b*.txt”或“r_*.txt”中使用这些语法吗???

4

1 回答 1

3

shell 正在尝试扩展b*.txt到当前目录中的匹配文件列表。一旦你的程序收到这些值,你的glob样子

@files = </home/ckhau/database/experiment/test/b1.txt b3.txt b3.txt>

这不是您想要的,如果b1.txt您的$RUN_DIR目录中没有文件,将无法找到任何文件

To prevent the shell globbing a wildcard file pattern you just need to put it in quotes, so your command becomes

perl Test.pl 'b*.txt'

Beyond that, your program really needs improving. You should always use strict and use warnings at the head of all your programs, and declare every variable at its point of first use; you should really use just the first element of @ARGV as your file pattern, instead of the whole array; and it is wrong to put scalar variables in quotes when you simply want their contents

Take a look at this refactoring of your original

#!/usr/bin/perl

use strict;
use warnings;

my $run_dir="/home/ckhau/database/experiment/test";

my $pattern = "$run_dir/$ARGV[0]";

my $index = -999; 
my @files = glob $pattern;

foreach my $file (@files) {
  my $script = "perl abc.pl '$file'";
  system $script;
}

Update

If you really want to have multiple wildcard patterns as parameters to Test.pl then you must patch the $run_dir directory onto the beginning of each of them. The best way to do this is to employ the File::Spec module's rel2abs function. The complete script would look like this

#!/usr/bin/perl

use strict;
use warnings;

use File::Spec;

my $run_dir="/home/ckhau/database/experiment/test";

my $pattern = join ' ', map File::Spec->rel2abs($_, $run_dir), @ARGV;

my $index = -999;
my @files = glob $pattern;

foreach my $file (@files) {
  my $script = "perl abc.pl '$file'";
  system $script;
}
于 2012-09-17T01:57:27.790 回答