Search code examples
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:

    • Reading from and writing to a file at the same time is hard. Your code, for example, would just write all over the existing data in the file
    • Using a bareword filehandle (CONFIG) instead of a lexical variable and two-arg open() instead of the three-arg version (open my $config_fh, '+<', $config') makes me think you're using some pretty old Perl tutorials
    • Using chop() instead of chomp() makes me think you're using some ancient Perl tutorials
    • You seem to have an extra $ in your regex - ^$apple$ should probably be ^apple$

    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";
      }
    }