【问题标题】:Cannot find argument passed to program called using Perl "system" command找不到传递给使用 Perl“系统”命令调用的程序的参数
【发布时间】:2011-07-06 06:04:09
【问题描述】:

我正在编写一个 Perl 脚本来对目录中的每个文件运行一个外部程序。该程序将文件从一种格式转换为另一种格式。这是交易...

当我从命令行运行程序时,一切正常:

computer.name % /path/program /inpath/input.in /outpath/output.out
converting: /inpath/input.in to /outpath/output.out

computer.name %

这是我编写的用于转换目录中所有文件的代码(在"file_list.txt" 中列出):

#!/usr/bin/perl -w

use warnings;
use diagnostics;
use FileHandle;
use File::Copy;

# Set simulation parameters and directories
@test_dates = ("20110414");
$listfile = "file_list.txt";
$execname = "/path/program";

foreach $date (@test_dates)
{
    # Set/make directories
    $obs_file_dir = "inpath";
    $pred_file_dir = "outpath";
    mkdir "$pred_file_dir", 0755 unless -d "$pred_file_dir";

    # Read input file names to array
    $obs_file_list = $obs_file_dir . $listfile;
    open(DIR, $obs_file_list) or die "Could not open file!";
    @obs_files = <DIR>;
    close(DIR);

    # Convert and save files
    foreach $file (@obs_files)
    {    
        $file =~ s/(\*)//g;
        $infile = $obs_file_dir . $file;
        $outfile = $pred_file_dir . $file;
        $outfile =~ s/in/out/g;
        print $infile . "\n";
        @arg_list = ($execname, $infile, $outfile);
        system(@arg_list);
    }
}

输出显示列表中每个文件的以下错误:

computer.name % perl_script_name.pl
/inpath/input.in
converting: /inpath/input.in to /outpath/output.out

unable to find /inpath/input.in
stat status=-1
error while processing the product

我验证了每个文件都在正确的位置,但不知道为什么会出现此错误。为什么找不到文件?当我使用命令行手动传递参数时,没问题。当我通过 system 调用通过变量传递参数时,即使路径和文件名正确,也找不到它们。

非常感谢您的建议!

【问题讨论】:

  • 没有什么明显的错误......你肯定它正在运行的命令是正确的吗?我会在你运行系统之前输出 join(" ", @arg_list) 的结果,看看粘贴到你的 shell 中是否有同样的效果。
  • /path/program 是脚本吗?如果是这样,该系统调用调用您的 $SHELL 来执行命令。如果是这种情况,您的 .cshrc / .tcshrc / .bashrc 是否会为您的主目录创建一个新的 shell chdir?在 /path/program 中添加 pwd 命令,这样就可以看到当前的工作目录了。

标签: perl command system arguments


【解决方案1】:

您的文件列表 (@obs_files) 来自通过 @obs_files = &lt;DIR&gt;; 读取文件

当您这样做时,数组的每个元素将是文件中的一行(例如目录列表),该行由换行符终止

使用前需要通过chomp($file)去掉换行符。

请注意,s/(\*)//g; 不会删除尾随的换行符!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2011-08-11
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    相关资源
    最近更新 更多