【问题标题】:Perl: opening a file, and saving it under a different name after editingPerl:打开一个文件,并在编辑后以不同的名称保存它
【发布时间】:2011-01-05 11:45:10
【问题描述】:

我正在尝试编写配置脚本。 对于每个客户,它会询问变量,然后写几个文本文件。

但是每个文本文件都需要多次使用,所以不能覆盖它们。我希望它从每个文件中读取,进行更改,然后将它们保存到 $name.originalname。

这可能吗?

【问题讨论】:

  • 这不是很清楚。您能否告诉我们“多次使用”是什么意思,以及您尝试过什么
  • 我还没有尝试任何东西,我正在计划中。 “多次使用”是指同一文件用于不同的变量集。因此它需要保持不变。

标签: perl file-handling


【解决方案1】:

假设您要读取一个文件,逐行对其进行更改,然后写入另一个文件:

#!/usr/bin/perl

use strict;
use warnings;

# set $input_file and #output_file accordingly

# input file
open my $in_filehandle, '<', $input_file or die $!;
# output file
open my $out_filehandle, '>', $output_file or die $!;

# iterate through the input file one line at a time
while ( <$in_filehandle> ) {

    # save this line and remove the newline
    my $input_line = $_;
    chomp $input_line;

    # prepare the line to be written out
    my $output_line = do_something( $input_line );

    # write to the output file
    print $output_line . "\n";

}

close $in_filehandle;
close $out_filehandle;

【讨论】:

    【解决方案2】:

    你想要像Template Toolkit 这样的东西。您让模板引擎打开一个模板,填写占位符,然后保存结果。你不应该自己做任何魔法。

    对于非常小的工作,我有时会使用Text::Template

    【讨论】:

      【解决方案3】:

      下面的代码希望为每个客户找到一个配置模板,例如,Joe 的模板是joe.originaljoe,并将输出写入joe

      foreach my $name (@customers) {
        my $template = "$name.original$name";
        open my $in,  "<", $template or die "$0: open $template";
        open my $out, ">", $name     or die "$0: open $name";
      
        # whatever processing you're doing goes here
        my $output = process_template $in;
      
        print $out $output           or die "$0: print $out: $!";
      
        close $in;
        close $out                   or warn "$0: close $name";
      }
      

      【讨论】:

      • 我已经想通了:我忘记了 perl 不像其他脚本那样......“流动”。我贴了一个 $customer_name = "placeholder";在那里,得到一个名为 CPE_Option_A.txt.placeholder 的文件。所以我认为问题在于我必须确保它最后复制文件。
      【解决方案4】:

      为什么不先复制文件,然后编辑复制的文件

      【讨论】:

      • 啊,好吧,我试试看 :) 看起来很明显,但我是菜鸟
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2012-12-31
      相关资源
      最近更新 更多