[perl-python] 20050126 find replace strings in file

Jürgen Exner jurgenex at hotmail.com
Wed Jan 26 18:51:06 EST 2005


Xah Lee wrote:
[...]
> In perl, similar code can be achieved.
> the following code illustrates.
>
> if (scalar @ARGV != 4)

Why scalar()? The comparison already creates a scalar context, no need to 
enforce it twice.

>  {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];

Ouch, how ugly. What's wrong with a simple
    my ($one, $two, $three, $four) = @ARGV;

or the standard way using shift
    for ($one, $two, $three, $four) {
        $_ = shift;
    }

> open(F1, "<$infile") or die "Perl fucked up. Reason: $!";
> open(F2, ">$outfile") or die "Perl fucked up. Reason: $!";

Really? Usually it's either the OS or the user (disk full, no write 
permissions, wrong file name, ...)

> while ($line = <F1>) {

Why $line? It doesn't serve any useful purpose here.

> chomp($line);

Why chomp()? It doesn't serve any useful purpose here.

> $line =~ s/$stext/$rtext/g;

If you would not have used $line above then you would not need the binding 
here.

> print F2 "$line\n";

If you would not have chomped the line above then you would not need to add 
the newline back here. A simpler
    print F2 $_;
would have sufficed

> }
> close(F1) or die "Perl fucked up. Reason: $!";
> close(F2) or die "Perl fucked up. Reason: $!";

I find this highly unlikely. If at all then the OS failed to complete the 
close.

jue 





More information about the Python-list mailing list