Reputation: 45
I'm trying to insert/add a line 'COMMENT DUMMY' at the beginnig of a file as a first row if /PATTERN/ not found. I know how to do this with OPEN CLOSE function. Probably after reading the file it should look something like this:
open F, ">", $fn or die "could not open file: $!"; ;
print F "COMMENT DUMMY\n", @array;
close F;
But I have a need to implement this with the use of the Tie::File function and don't know how.
use strict;
use warnings;
use Tie::File;
my $fn = 'test.txt';
tie my @lines, 'Tie::File', $fn or die "could not tie file: $!";
untie @lines;
Upvotes: 2
Views: 251
Reputation: 132863
The point of tie is to make one thing behave like another. Since you are tie-ing a file to an array, it now acts like an array. You use array operators to do whatever you need to do.
Upvotes: 1
Reputation: 37146
Kinopiko's pointed you in the right direction. To complete your need, I'd do the following:
use strict;
use warnings;
use Tie::File;
my $fileName = 'test.txt';
tie my @lines, 'Tie::File', $fileName or die "Unable to tie $fileName: $!";
unshift @lines, "DUMMY COMMENT\n" if grep { /PATTERN/ } @lines;
untie @lines;
if
statement comes after the unshift
statement in writing, it gets evaluated first.grep
, think of it as a list filter. Basically, it takes your @lines
list and uses it to create a new list with just elements that match /PATTERN/
.if
statement evaluates to true if the new, filtered list contains any elements, and false if the list is empty. Based on this, the "DUMMY COMMENT\n"
line is added to your @lines
list.Upvotes: 1
Reputation:
unshift
works:
use Tie::File;
my $fn = 'test.txt';
tie my @lines, 'Tie::File', $fn or die "could not tie file: $!";
unshift @lines, "COMMENT DUMMY\n";
untie @lines;
Upvotes: 2