Perl Delete Line: Guide & Examples

In Perl, you can delete a specific line by reading a file and writing only the lines that are needed to a new file. Below is an example code demonstrating how to delete lines that contain a specific string.

use strict;
use warnings;

my $input_file = 'input.txt';
my $output_file = 'output.txt';
my $string_to_delete = 'delete this line';

open(my $input_fh, '<', $input_file) or die "Cannot open $input_file: $!";
open(my $output_fh, '>', $output_file) or die "Cannot open $output_file: $!";

while (my $line = <$input_fh>) {
    if ($line !~ /$string_to_delete/) {
        print $output_fh $line;
    }
}

close($input_fh);
close($output_fh);

# Rename the output file to the original file
rename $output_file, $input_file or die "Cannot rename $output_file to $input_file: $!";

In this example, we start by defining the input file “input.txt”, the output file “output.txt”, and the string to be deleted “delete this line”. Then we open the input file and output file, and iterate through each line of the input file. If a line does not contain the specified string to be deleted, it is written to the output file. Finally, we close the file handles and rename the output file to the original input file name, effectively deleting the specific line.

bannerAds