1

我创建了一个文件,其中包含第 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

ETC

4

2 回答 2

3

I think this is what you want to do...

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);

Running the code:

$ 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
于 2013-05-09T17:08:15.820 回答
3

使用领带::文件

#! /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
于 2013-05-10T02:58:51.497 回答