【问题标题】:Perl script to modify one file taking values from second filePerl 脚本修改一个文件,从第二个文件中获取值
【发布时间】:2019-03-14 14:10:35
【问题描述】:

我编写了一个处理两个文件的 Perl 脚本,文件 1 包含一些文本,其中 'ABC' 需要替换为第二个文本文件中存在的值列表。

文件1.txt:

Name     -> ABC

Record   -> Exists

Presence -> Existing_ABC

文件2.txt:

John

Claude

Kepler

Shane

Austin

我想用 John 替换 File1 中的“ABC”,然后应该再次使用原始 File1,并且应该用 Claude 替换“ABC”并与第一次迭代合并,依此类推,直到最后一个条目文件 2。 所以,目前脚本只给出一个值“John”的输出,它不从列表中获取其他值。

最终的 Output.txt 文件应该是这样的:

Name     -> John

Record   -> Exists

Presence -> Existing_John


Name     -> Claude

Record   -> Exists

Presence -> Existing_Claude

.

.

.

.
.


(#till Austin)

请在我的脚本中找出错误并提前致谢:->

#!/usr/bin/perl

use strict;

use warnings;

my @blockList   =  load_block_list();

my $rules_file  =  'File1.txt';

my $out_file    =  'out.txt';  

open( my $rules,  '<',  $rules_file  );

open( my $out,    '>',  $out_file  );

my $Orig_line;

my $new_line;

my $key;


foreach my $Element (@blockList) {

    while($Orig_line=<$rules>) {

        chomp($Orig_line);

        $new_line = $Orig_line;

        if($Orig_line =~ m/ABC/) {
            $new_line =~ s/ABC/$Element/;
        }

        print {$out} "$new_line\n";

    }
}

sub load_block_list
{
    my $block_list = "File2.txt";

    open(DAT, $block_list) || die("Could not open file $block_list!");
    my @lines=<DAT>;
    close(DAT);

    my @retVal = ();
    foreach my $line (@lines) {
        $line =~ s/[\r\n]+//g;
        push(@retVal,$line),
    }
    return @retVal;
}

【问题讨论】:

    标签: perl file-handling


    【解决方案1】:

    在迭代 @blockList 之前,您应该阅读 File1.txt。 像这样的:

    ...
    my @template = load_template(); 
    my @blockList = load_block_list();
    ...
    foreach my $Element (@blockList) {
        foreach my $Orig_line (@template) {
    ...
    

    load_template 应该类似于load_block_list

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2016-08-28
      相关资源
      最近更新 更多