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 fil开发者_如何学JAVAe: $!";
untie @lines;
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;
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;
Explanation
- You may already know that although the
if
statement comes after theunshift
statement in writing, it gets evaluated first. - When you see
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/
. - The
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.
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.
精彩评论