[Israel.pm] -i and more
Offer Kaye
oferk at oren.co.il
Mon Apr 19 05:59:59 PDT 2004
> Hi,
>
> I need to write a scipt that gets: inFileName outFileName oldStr newStr
>
> The script should be a simple one that replaces all occurances of oldStr
> with newStr from inFileName, and save it in outFileName
>
> I can do it in the long way or in the shorter (and much simpler ) way.
>
> My questions:
>
> 1. the -i flag saves the output file with the original name
> +suffix/prefix. In this case I need to use a name given by the user.
> 2. The oldStr/newStr may contain wierd characters such as */\@
> etc. I do
> I prevernt meta characters to affect my perl code ?
>
> Thanks
>
> Yossi
>
1. Since you are talking about a totally different name here, I don't see
how using the -i switch is usefull. It really isn't that long to write
something that opens 2 filehandles...
2. Use the "quotemeta" function, or the "\Q\E" quote operator.
Example code:
<code>
use warnings;
use strict;
my ($inFileName, $outFileName, $oldStr, $newStr) = @ARGV;
$oldStr = quotemeta $oldStr;
open(IN,"$inFileName") or die "Couldn't open $inFileName for reading: $!\n";
open(OUT,">$outFileName") or die "Couldn't open $outFileName for writing:
$!\n";
while(<IN>) {
s/$oldStr/$newStr/g;
print OUT;
}
close(IN) or die "Couldn't close $inFileName after reading: $!\n";
close(OUT) or die "Couldn't close $outFileName after writing: $!\n";
</code>
--
Offer Kaye
More information about the Perl
mailing list