in reply to Word Replacing
Perl (not PERL) does not, usually, loop through all the lines of the file; to make it do so see perlrun.
I've a few questions about your post:
I'm explicitly opening the file for writing as I don't want to assume that the -i runtime option is specified. Also, I'm assuming that case is not important and that you want every instance of $oldword replaced.use strict; use warnings; sub subsitute { (my $filename, my $oldword, my $newword) = @_[0..2]; local $/; if(open(my $fh, "<", $filename)){ my $contents = <$fh>; $contents =~ s/\b$oldword\b/$newword/ig; close($fh); if(open($fh, ">", $filename){ print $fh $contents; close($fh); return 1; # for success } else{ warn "Could not open $filename for writing because $!; skippin +g it\n"; return undef; } } else { warn "Could not open $filename because $!; it will be skipped\n"; return undef; } }
You will have to do some more checks than just to see if the file is binary or not. Obviously, you should make sure that you've got correct rights to change the file. I would also advise that you copy the file, instead of changing it in place, until after you've thoroughly tested the code. You would, for example, not want to change source code in such a way as to introduce a syntax error or undefined external reference. And changing system("cp $oldfile $newfile"); to system("rm $oldfile $newfile"); could tend to be career inhibiting.
emc
Any New York City or Connecticut area jobs? I'm currently unemployed.
There are some enterprises in which a careful disorderliness is the true method.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Word Replacing
by xoddam (Novice) on Jun 04, 2007 at 21:41 UTC | |
by xoddam (Novice) on Jun 04, 2007 at 22:29 UTC | |
by swampyankee (Parson) on Jun 05, 2007 at 03:46 UTC |