#!/usr/bin/perl use Algorithm::LUHN qw(is_valid); use autodie; # Automatic errors on file problems. use strict; use warnings; # This is the name of the file we want to modify. my $filename = 'test_ccc9999.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 (my $row = <$input_h>) { while ($row =~ /(3[47]\d{13})/g) { if (is_valid("$1")) { print "$1\n"; $1 =~ s/(3[47]\d{9})(\d{4})/XXXXXXXXXXX$2/g; } #print "$1\n"; } # 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;