fileperlwritefile

perl add line into text file


I am writing a script to append text file by adding some text under specific string in the file after tab spacing. Help needed to add new line and tab spacing after matched string "apple" in below case.

Example File:

apple
<tab_spacing>original text1
orange
<tab_spacing>original text2

Expected output:

apple
<tab_spacing>testing
<tab_spacing>original text1
orange
<tab_spacing>original text2

What i have tried:

use strict;
use warnings;
my $config="filename.txt";
open (CONFIG,"+<$config") or die "Fail to open config file $config\n";
    while (<CONFIG>) {
        chop;
        if (($_ =~ /^$apple$/)){
            print CONFIG "\n";
            print CONFIG "testing\n";
        }
}
      close CONFIG;

Solution

  • Some pretty weird stuff in your code, to be honest:

    Also, Tie::File has been included with Perl's standard library for over twenty years and would make this task far easier.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Tie::File;
    
    tie my @file, 'Tie::File', 'filename.txt' or die $!;
    
    for (0 .. $#file) {
      if ($file[$_] eq 'apple') {
        splice @file, $_ + 1, 0, "\ttesting\n";
      }
    }