Reputation: 105
I have more code before this which populates the array @a_nam. Now I want to append the elements in the array @a_nam at the end of the line shown below in abc.txt. I tried something but its not working. please give your inputs. edited: i tried "+>>" which didnt work.
## NAME_id , course, Fall 10 ,spring 11, ........
open my $file, '+>>', 'abc.txt' or die "failed : $!";
while (<$file>) {
chomp;
if (/^## NAME(.*)/) {
print $file join ",", @a_nam;
}
}
close($file);
Upvotes: 2
Views: 204
Reputation: 4088
Simple example using Tie::File
I'm not going to repeat @choroba, as he's already explained why your example doesn't work.
UPDATED. It will now append the array
to the end of the line, instead of removing it.
use warnings;
use strict;
use Tie::File;
my @a_nam = qw(append some stuff);
my $match = "## NAME";
tie my @lines, 'Tie::File', "abc.txt" or die "failed: $!";
for my $line (@lines){
if( $line =~ /^($match.*)/ ) {
$line = $1 . ", " . join ', ', @a_nam;
}
}
untie @lines;
File before:
1 blah blah
2 ## NAME, foo, bar, baz
3 whatever lines here
File after:
1 blah blah
2 ## NAME, foo, bar, baz, append, some, stuff
3 whatever lines here
Upvotes: 3
Reputation: 241758
You open the file for appending
open my $file, '>>'
but then you try to read from the file
while (<$file>)
This is not possible. Open the file for reading and write to another file. At the end, rename the old file to a backup and the new file to the original.
Upvotes: 4