in reply to Compare two file text input, compare it, replace and write new file

open (DFILE,$dfile) or die "can not open"; open (SFILE,$sfile) or die "can not open"; open (TFILE,"> $tfile") or die "can not open";

That would be better as:

open DFILE, '<', $dfile or die "can not open '$dfile' because: $!"; open SFILE, '<', $sfile or die "can not open '$sfile' because: $!"; open TFILE, '>', $tfile or die "can not open '$tfile' because: $!";


$words{$key} .= exists $words{$key} ? "$val" : $val;

That would be better as:

$words{$key} .= $val;


while (my $s = <SFILE>) { chomp($s); my @words = split / /, $s;

That would be better as:

while ( <SFILE> ) { my @words = split;


for my $i (0 .. $#words) { $words[$i] = $words{$words[$i]} if (exists($words{$words[$i]})) }

That would be better as:

for my $word ( @words ) { $word = $words{ $word } if exists $words{ $word }; }


print TFILE join(' ', @words),$/; print TFILE "<br>";

That would be better as:

print TFILE "@words\n<br>";


The code above work if only if the source.txt contain keys separated with space,

\ca \ra \ka \tl

but fail to work if source.txt is

\ca\ra\ka\tl
$ perl -le'$_ = q/\ca\ra\ka\tl/; print; print for split /(?=\\)/' \ca\ra\ka\tl \ca \ra \ka \tl

Replies are listed 'Best First'.
Re^2: Compare two file text input, compare it, replace and write new file
by wa2nlinux (Novice) on Feb 15, 2012 at 01:55 UTC
    OK the newest code :
    #!/usr/bin/perl use strict; use warnings; my $dfile = 'data'; my $sfile = 'source.txt'; my $tfile = 'target.html'; open DFILE, '<', $dfile or die "can not open '$dfile' because: $!"; open SFILE, '<', $sfile or die "can not open '$sfile' because: $!"; open TFILE, '>', $tfile or die "can not open '$tfile' because: $!"; my %words; while (<DFILE>) { chomp; my ($key, $val) = split /:/; $words{$key} = $val; }; while ( <SFILE> ) { my @words = split /(?=\\)/; for my $word ( @words ) { $word = $words{ $word } if exists $words{ $word }; } print TFILE "@words\n<br>"; } close(SFILE); close(DFILE); close(TFILE);
    having source.txt :
    \ca\ra\ka\tl \ca\ra\ka\tl
    the last character of line (\tl) not replace by value on data. The result in target.html is :
    &#xa15 &#xa16 &#xa17 \tl <br>&#xa15 &#xa916 &#xa17 \tl
      Solved by adding chomp
      while ( <SFILE> ) { chomp my @words = split /(?=\\)/; for my $word ( @words ) { $word = $words{ $word } if exists $words{ $word }; } print TFILE "@words\n<br>"; }
      another question: is it OK, if I used hash array my "data" (DFILE) on that program contain about 5000 lines ?
      my %words; while (<DFILE>) { chomp; my ($key, $val) = split /:/; $words{$key} = $val; };