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



Question:

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;   


Solution:1

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;  


Solution:2

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.


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »