April 14, 2012
Perl Read File Line by Line
The following Perl code reads and replace some text in a file. Two code snippets are provided to read a small file and a large file:
Reading a Small File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#!/usr/bin/perl # Open file for reading open(IN,"in.txt") or die "Cannot open file: $!\\n"; # Open file for writing open(OUT, ">out.txt"); # Read the entire file into an array @file = ; # Line by line foreach $line (@file) { # Replace text in line $line =~ s/txt1/txt2/g; # Print the modified line print OUT $line; } # Close files close IN; close OUT; |
Reading a Large File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#!/usr/bin/perl # Open file reading open(IN,"in.txt") or die "Cannot open file: $!\\n"; # Open file for writing open(OUT, ">out.txt"); # For each line while() { # Replace text in line $_ =~ s/txt1/txt2/g; # Write current line print OUT $_; } # Close files close IN; close OUT; |