Reputation: 674
I am trying to do a replace of a specific set of characters in a file in Perl but it does not seem to work, here is my code.
my $file = shift;
open(FILE, "$file") or die "File not found";
while (<FILE>){
$data .=$_
}
$data =~ s/[^A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}\s?[0-9]{2}\s?[0-9]{2}\s[0-9]{2}\s?[A-DEM]{0,1}$/XX012345X/g;
I know that my pattern matching works for finding the set of characters, I am not entirely sure the replace works. However, my main concern is the Perl code. The file remains untouched after I run it.
Sample File.
AB123456C Ab12345678 DG657465 GH123456FG
Upvotes: 0
Views: 1049
Reputation: 13792
The file your are opening is read only. So you need to open a temporary second file (File::Temp) where your write the $data variable, close it, remove the first file (unlink) and rename the temporary file to the desired name.
This SO question may be helpful.
Off topic note: please, use modern Perl approach to handle your files. For example:
open my $fh, "<", $filename or die "Cannot open file $filename"
See also this SO question. Avoid the use of package-global typeglob filehandles.
Upvotes: 0
Reputation: 67900
The code does not alter the file because you don't tell it to. You open the file for reading, not writing, plus you do not print anything.
If you want a quick way to handle this, just put your regex substitution in a file and use it as a source file. Like this:
Content of regex.pl:
s/[^A-CEGHJ-PR-TW-Z]{1}[A-CEGHJ-NPR-TW-Z]{1}\s?[0-9]{2}\s?[0-9]{2}\s[0-9]{2}\s?[A-DEM]{0,1}$/XX012345X/g;
One-liner:
perl -p regex.pl inputfile.txt > output.txt
This way you can quickly check the output. You can also pipe to a pager command or not at all.
Upvotes: 2