#!/usr/bin/perl use autodie; # Automatic errors on file problems. use strict; # This is the name of the file we want to modify. my $filename = 'modify-file.txt'; # We're going to create a temporary file. This avoids us having # to build up a potentially large string in memory. my $tempname = $filename . '.tmp'; do { # Open both files. Doing this using lexical file handles # within a "do" block means that when the end of the block # is reached, the files will be closed. open my $input_h, '<', $filename; # input handle open my $output_h, '>', $tempname; # output handle # Loop through each line of input. while (<$input_h>) { # Modify the line s/^>Sample_(\d+)_x(\d+)/>ID$1 $2/i; # Write it out. print $output_h $_; } }; # Delete the original file. unlink $filename while -f $filename; # Rename the temporary file to the original filename. rename $tempname => $filename;