[perl-python] 20050126 find replace strings in file

Eric Schwartz emschwar at fc.hp.com
Wed Jan 26 20:19:49 EST 2005

To follow up on Jurgen Exner's critique, I present Xah Lee's version, and
then my rewritten version.

"Xah Lee" <xah at xahlee.org> writes:
> if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 <sstr> <rstr>
> <file id1> <file id2>\n"}
> $stext=$ARGV[0];
> $rtext=$ARGV[1];
> $infile = $ARGV[2];
> $outfile = $ARGV[3];
> open(F1, "<$infile") or die "Perl fucked up. Reason: $!";
> open(F2, ">$outfile") or die "Perl fucked up. Reason: $!";
> while ($line = <F1>) {
> chomp($line);
> $line =~ s/$stext/$rtext/g;
> print F2 "$line\n";
> }
> close(F1) or die "Perl fucked up. Reason: $!";
> close(F2) or die "Perl fucked up. Reason: $!";

use warnings;
use strict;

if (@ARGV != 4) {
   die "Wrong arg! Unix BNF: $0 <sstr> <rstr> <file id1> <file id2>" 
my ($stext, $rtext, $infile, $outfile) = @ARGV;

open my $infh, '<', $infile
     or die "Error opening input file [$infile]: $!";
open my $outfh, '>', $outfile
     or die "Error opening output file [$outfile]: $!";

while(<$infh>) {
    print { $outfh } $_;
close($infh) or die "Error closing input file [$infile]: $!";
close($outfh) or die "Error closing output file [$outfile]: $!";

My version takes up more lines, but I don't count whitespace--
whitespace is not expensive, and when used properly adds greatly to
the readability of your program.

I've set followups to the only appropriate group for Mr. Lee's

Come to think of it, there are already a million monkeys on a million
typewriters, and Usenet is NOTHING like Shakespeare.
		-- Blair Houghton.

More information about the Python-list mailing list