thebourneid
thebourneid

Reputation: 45

How can I insert a line at the beginning of a file with Perl's Tie::File?

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

Answers (3)

brian d foy
brian d foy

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

Zaid
Zaid

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;

Explanation

  • You may already know that although the if statement comes after the unshift 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.

Upvotes: 1

user181548
user181548

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

Related Questions