Esteemed Monks,
I have files where I need to replace values in specific places. The standard line lengths ar 210 characters and I need to change the characters in positions 100 and 149 only. I also need to ignore any line that begins with a 2. When this outputs I need to preserve the lines beginning with a 2 and output each line until completion but I cannot get any "foreach" statement to function correctly. I would rather not load the file in memory as the files will often have up to a million lines each and this definitely takes a hit on CPU performance.
Any suggestions, solutions, or better ways of doing this are welcome.
Thanks in advance -- Perl Newbie
use File::Copy;
my($input_file) = $ARGV[0];
my($output_file) = $ARGV[1];
if ( !defined($input_file) || !defined($output_file) ) {
print "Error: usage: ss7jurisdiction input_file output_file\n";
}
else {
# -----Backup the input files in case of error-----
copy( $input_file, $input_file . ".bak" ) or
die "Could not backup file $input_file to $input_file.bak: $!\
+n";
# -----Attempt to open all of the files-----
open( INFILE, $input_file ) || die( "Could not read input file 1 (
+$input_file): $!" );
open( OUTPUT, "> " . $output_file ) || die( "Could not open output
+ file ($output_file): $!" );
while (<INFILE>) {
my $line = $_;
chomp($line);
# -----A line starting with a '2' is a header and is left unch
+anged
if ( $line !~ m/^2/ ) {
# -----Locate postions 100 and 149
$juris1 = substr( $line, 99, 1 );
$juris2 = substr( $line, 148, 1 );
$juris1 = "9";
$juris2 = "Z";
# -----Generate the output string-----
$output_line = substr( $line, 0, 98 )
. $juris1 . substr( $line, 100, 48 )
. $juris2 . substr( $line, 149, 61 )
. "\n";
print OUTPUT $output_line;
last;
}
}
# -----Close all of the files-----
close( INFILE );
close( OUTPUT );
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.