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?
There are a few ways to do what you require:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File
tie my @buffer, 'Tie::File', 'data.txt' or die "Cant open data.txt $!";
for ( @buffer ) {
s/Dood/Dude/ and last;
}
__END__
#!/usr/bin/perl
use strict;
use warnings;
local ( $^I, @ARGV ) = ( '', 'data.txt' );
while ( <> ) {
?Dood? && s/Dood/Dude/;
print;
}
__END__
#!/usr/bin/perl
use strict;
use warnings;
use Fcntl ':seek';
open my $FP, '+<', 'data.txt' or die "Cant open data.txt $!";
read $FP, my $buffer, -s $FP or die "Cant read from data.txt $!";
seek $FP, 0, SEEK_SET or die "Cant seek on data.txt $!";
$buffer =~ s/Dood/Dude/;
print $FP $buffer;
__END__
John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction. -- Albert Einstein
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/