Processing a Text File in Perl

Processing a Text File in Perl

Loading a text, processing the contents, and outputting a processed verssion of the file is a common task in Perl.

Sometimes it's light processing: rearrange the order of parts of each line. Sometime's it's heavier processing: collect a bunch of statistical data from the file and output a summary of the data with averages, mins, maxes, etc. In either case the following template is a handy starting point that shows the loading, some light processing, and writing the results to the output file. 

# Read in a file, process and optionally modify 
# each line, saving results to a new file.
# Sample usage:
# perl process.pl input.csv 
use strict;
use warnings;
 
my $infilename = $ARGV[0]; # Open input file for reading
open(my $infh, '<:encoding(UTF-8)', $infilename) 
	or die "Could not open file '$infilename' $!";
 
my $outfilename = 'output.csv'; # Open output file for writing
open(my $outfh, '>', $outfilename) 
	or die "Could not open file '$outfilename' $!";
 
while (<$infh>) { # Iterate through the input file	
 
	$_ =~ s/\R//; # Remove linebreaks 	
 
	# Add you own per-line processing here...
	# For example,
	if(/\d+/){ # if line contains number, modify and output to file
		print $outfh "Line with number: $_\n"; # 
	}
	else{ # otherwise, modify it a different way
		print $outfh "Line without number: $_\n";
	}
}

Add new comment

Guest

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.