user2320229
user2320229

Reputation: 71

Inserting a new value into an already created file - perl

I have a file created which has data in columns 0, 1 and 2. I now have a new variable called $percentage that has 11 values associated to it that I wish to add to column 3 of the file.

How do I do this without appending to the bottom of the file?

Currently my data looks like, but would like it formatted next to the existing data:

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

Upvotes: 1

Views: 85

Answers (2)

chrsblck
chrsblck

Reputation: 4088

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

Upvotes: 3

Julian Fondren
Julian Fondren

Reputation: 5619

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

Example:

$ 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

Upvotes: 3

Related Questions