On Aug 21, 4:33 am, xecro...@yahoo.com (Ron Weidner) wrote: > Recently, I was asked to find the first occurrence of a word in a text file > and replace it with an alternate word. This was my solution. As a new Perl > programmer, I feel like this solution was too C like and not enough Perl > like. So, my question is what would have been the Perl like solution to this > problem? > > In this example there is little risk of running out of memory reading the > file. But had this been a production environment or an unknown file size, I > would have had to consider that. > > #!/usr/bin/perl > use strict; > use warnings; > > #program finds the first occurrence of the word Dood and > #replaces it with the word Dude in the file data.txt. > > open FP, "+<", "data.txt" || die "Cant open data.txt " . $!; > > my @buffer = <FP>; > seek FP,0,0; > my $do_replace = 1; #used to control replacing in multiline files. > my $line; > my $data; > foreach $data (@buffer) > { > if ($do_replace == 1) > { > $line = $data; > $data =~ s/Dood/Dude/; > if ($line ne $data) > { > $do_replace = 0; #we did a substitution so do no more. > } > } > print FP $data;} > > close FP; > > #Test data > #Dude! Where's my car? > #Dood! Where's my car? > #Dood! Where's my car? > >
If you're permitted a one-liner: perl -pi.bak -e '$c=s/Dood\/Dude/ if !$c++' file -- Charles DeRykus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/