【问题标题】:How do I write contents to file in perl如何在perl中将内容写入文件
【发布时间】:2013-12-28 23:39:29
【问题描述】:

当我尝试将内容写入文件时,文件返回空白。不知道这里发生了什么。我知道正则表达式正在工作。我怀疑问题出在我写文件的方式上。

#!/usr/bin/perl
@files = </home/vnc/Downloads/test/*.json>;
my $myfile;
foreach $file (@files) {
    print $file . "\n";
    open(IN,'<',$file) or die $!;
    while(<IN>) {
        $_ =~ s/^(.*?)\[//;
        $_ =~ s/\](?=[^.]*$)//;
        $myfile = $_;
        # print $myfile;
    }
    close(IN);
    open(OT,'>',$file) or die $!;
    while(<OT>) {
        print(OT $myfile);
    }
    close(OT);
    # $file =~ s/^(.*?)\[//;
} 

【问题讨论】:

  • 我以前没见过print(OT $myfile);。标准符号没有括号:print OT $myfile;。你应该使用use strict;use warnings; 来确保你没有犯任何愚蠢的错误。我还建议使用词法文件句柄:open my $in, '&lt;', $file or die "Failed to open $file ($!)"; 等。
  • 别担心,我想通了。

标签: perl file-handling


【解决方案1】:

据我了解,您的方法是错误的。您处理整个文件,用正则表达式替换某些内容,但您没有将其写入任何地方。稍后您以写入模式打开一个文件,但循环无用,因为它是空的。

在我看来,处理这种情况的最简单方法是使用修改文件的$^I 变量。这里是一个单行示例(未测试):

perl -i.bak -pe 's/^(.*?)\[//; s/\](?=[^.]*$)//' /home/vnc/Downloads/test/*.json

【讨论】:

  • 很好看;我错过了明显的!
  • 一旦我在我的问题下实施了 cmets 中的建议,脚本就可以正常工作。我暂时避免使用单行,因为我打算一次性进行更多的正则表达式处理和 shell 命令。
  • @Julian:如果单行让你害怕,你可以使用变量$^I 和处理来自@ARGV 的文件来获得相同的行为。一旦你习惯了它就会避免很多头痛。
  • 您不必因为使用单行工具而放弃源文件,您可以将正则表达式和您希望在单行中包含的任何代码存储在一个文件中,并且在没有-e 开关的情况下运行它,带有文件名参数:perl -pi yourfile.pl /home/vnc/Downloads/test/*.json
  • 我实际上只是在运行脚本时使用“perl exp.txt”。不过感谢您的建议。
【解决方案2】:

要在 perl 脚本中就地修改文件列表,您也可以使用这种方法。文件内容加载到数组@content,修改后写入原文件:

#!/usr/bin/perl

use strict;

# Example: Modifying a list of files in-place within a perl script

foreach my $file (</home/vnc/Downloads/test/*.json>) {
    # Open read-write (+<)
    open my $f, "+< $file" or die "$!\n";

    # read the lines:
    my @content = <$f>;

    # change the lines:
    @content = map { s/foo/bar/; $_ } @content;

    # empty the file
    truncate $f, 0;

    # rewind to beginning of file
    seek $f, 0, 0;

    # print new content to file
    print $f @content;

    close $f;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多