【问题标题】:How do I redirect the output of a Perl script to another file in %TEMP%?如何将 Perl 脚本的输出重定向到 %TEMP% 中的另一个文件?
【发布时间】:2011-04-08 16:03:32
【问题描述】:

我需要 Windows 上的 Perl 脚本,它从文件中删除换行符并将所有行合并为一行,然后将另一个文件写入 Windows 系统上的 %temp% 目录。例如,这个脚本是删除换行符并创建一个单行并写入%TEMP%中的另一个文件。

我有删除换行符但输出到 STDOUT 的脚本。我无法在 %TEMP% 中创建文件并将输出重定向到该文件。

以下是我的脚本不起作用:

my $inFile = $ARGV[0];
$ENV{'TEMP'} = 'C:\\TEMP';

if ($inFile eq "") {
    print "Input file is missing\n";
    print "perl file_into_one_line.pl <input fil>\n";
    exit 0;
}

open(INFILE, "< $inFile") || die "$0, FEJL: can't open $inFile: $!";
foreach (<INFILE>) {
    chomp;
    if (eof()) {    # check for end of last file
        print "$_\n";
    } else {
        open FILE, ">$ENV{'TEMP'}//temp//tst.txt" or die;
        print FILE "${_}$separator";
    }
}

close(INFILE);

【问题讨论】:

  • 请附上您目前编写的脚本。
  • 你可以像这样运行你的脚本:perl myscript.pl &gt;%TEMP%/file.txt
  • inFile 可以是undef,所以检查!defined $inFile || $inFile eq ""

标签: perl


【解决方案1】:

请注意,%TEMP% 是用于访问环境变量的 DOS 语法。您可以通过 %ENV 哈希访问 perl 中环境变量的值,如下所示:

$ENV{k}

其中 k 是一个字符串表达式,它给出了变量的名称。在你的 Windows 命令行中试试这个:

perl -e "print $ENV{'TEMP'};"

从这里开始,您应该可以完成剩下的工作了。

【讨论】:

    【解决方案2】:

    脚本应该是:

    my $separator = " "; # I think you should have this some where~~~
    
    my $inFile = $ARGV[0];
    $ENV{'TEMP'} = 'C:\\TEMP';
    
    if ($inFile eq "") {
        print "Input file is missing\n";
        print "perl file_into_one_line.pl <input fil>\n";
        exit 0;
    }
    
    open(INFILE, "< $inFile") || die "$0, FEJL: can't open $inFile: $!";
    open FILE, ">$ENV{'TEMP'}\\tst.txt" or die $!;
    foreach (<INFILE>) {
        chomp;
        print FILE "${_}$separator";
    }
    
    print FILE "\n";
    
    close(INFILE);
    close(FILE);
    

    【讨论】:

    • 在 ast 行之后没有$separator。所以代替foreach循环我可以建议像print FILE join $separator, map {chomp; $_} &lt;INFILE&gt;;这样的sg
    猜你喜欢
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2020-01-06
    • 2013-04-30
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多