A common idiom in Perl 5 is "slurping". Slurping is the process of reading a file into an array, split by line breaks. You can then iterate over the array and perform an operation on each line. This is the basic input mechanism I use to process all sorts of data/text files.
The basic slurp goes like this...
Open a file in read mode and assign it a file handle:
open(FILE, 'foo.txt') or die $!;
Read (slurp) the file into an array of lines (splitting the file on newlines):
@file = <FILE>;
You can then process the array in a foreach loop and "Un-slurp" (De-slurp?) it back to the file system like this...
Now we have an array which we can iterate through and do whatever we want with each line:
foreach (@file) { # do something here }
Re-open the file in overwrite mode:
open(FILE, '>foo.txt') or die $!;
Print the contents of the array back to the file:
print FILE @file;
The following script shows some slurping in a action. This script will read a file named "foo.txt" and replace all intances of "foo" with "bar"
#!/usr/bin/perl replace('foo.txt', 'foo', 'bar'); sub replace { ($filename, $original, $substituted) = @_; open(FILE, $filename) or die $!; @file = ; foreach (@file) { s/$original/$substituted/g; } open(FILE, '>foo.txt') or die $!; print FILE @file; }
Copyright © 2006-2008 Corey Goldberg
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.