将新值插入已创建的文件中 - perl

时间:2013-05-09 16:05:37

标签: perl file

我创建的文件包含第0,1和2列中的数据。我现在有一个名为$ percentage的新变量,它有11个与之关联的值,我希望将其添加到文件的第3列。

如何在不附加到文件底部的情况下执行此操作?

目前我的数据看起来像,但希望它在现有数据旁边格式化:

title name number 
title name number 
title name number 
title name number 
                  $percentage value 1
                  $percentage value 2
                  $percentage value 3
                  $percentage value 4

2 个答案:

答案 0 :(得分:3)

我认为这就是你想要做的......

use warnings;
use strict;

use File::Copy;

my $target_file = "testfile";
my $tmp_file = "$target_file.new";
my $str = "some string with stuff";

open my $fh, "<", "testfile";
open my $w_fh, ">>", "testfile.new";

# loop over your current file, one line at a time
while( my $line = <$fh> ){
    # remove the '\n' so we can add to the existing line
    chomp $line;
    # add what you'd like, plus the '\n'
    my $full_line = "$line $str\n";
    # and print this to a tmp file
    print $w_fh $full_line;
}
close $fh;
close $w_fh;

unlink $target_file or die "unable to delete $target_file: $!";
# use the File::Copy sub 'move'
# to rename the tmp file to the original name
move($tmp_file, $target_file);

运行代码:

$ cat testfile
this is three
this is three
this is three
$ test.pl
$ cat testfile
this is three some string with stuff
this is three some string with stuff
this is three some string with stuff

答案 1 :(得分:3)

使用Tie::File;

#! /usr/bin/env perl
use common::sense;
use Tie::File;

tie my @f, 'Tie::File', 'foo' or die $!;

my $n;
for (@f) {
  $_ .= ' $percentage value ' . $n++;
}

untie @f;

示例:

$ cat foo
title name number
title name number
title name number
title name number
$ perl tie-ex 
$ cat foo
title name number $percentage value 0
title name number $percentage value 1
title name number $percentage value 2
title name number $percentage value 3