Problem Description:
I am trying to copy one file into another, filea -> copy into -> fileb,
filea is smaller than fileb. Say filea is 100 bytes and fileb is 120
bytes. After the copy fileb is still 120 bytes, the first 100
come from filea and the last 20 are the original last 20 from
fileb.
Here is the code:
-------------------------------------------------
#! /bin/perl
use FileHandle;
use File::Copy;
%testHash = qw ( fen ton pat rick dan boy );
$file1 = new FileHandle;
$file1->open ("< /tmp/file1" ) or die "Can't open file";
snr ( $file1, \%testHash );
sub snr
{
$file2 = new FileHandle;
$file2->open ("+>/tmp/file2") or die "D1:$!";
copy ( $file1, $file2 ) or die "D2:$!";
$file3 = new FileHandle;
$file3->open ("+>/tmp/file3") or die "D5:$!";
foreach $searchWord ( keys ( %$hashRef ))
{
seek ( $file2, 0, 0 ) or die "D3:$!";
seek ( $file3, 0, 0 ) or die "D7:$!";
while ( $_ = $file2->getline )
{
print "Looking at: $_\n Searching for: $searchWord";
if (/$searchWord/)
{
print " -> found\n";
$file3->print ("$$hashRef{$searchWord}\n");
}
else
{
print " -> notFound\n";
$file3->print ("$_");
}
}
seek ( $file2, 0, 0 ) or die "D8:$!";
seek ( $file3, 0, 0 ) or die "D9:$!";
copy ( $file3, $file2 ) or die "D6: $!";
exit 0;
}
}
Contents of file1
----------------------------------------
rw-r-- 1 ewmaint pscop 206 Mar 15 13:44 affectedFile.bak.gz
-rw-rw-r-- 1 ewmaint pscop 112 Mar 15 13:49
searchNreplacePairs
-rw-rw-r-- 1 ewmaint pscop
fen is cool
Output
---------------------------------------
742 dgi:/tmp% /usr/mda/autoInstall/test3.pl
Looking at: rw-r-- 1 ewmaint pscop 206 Mar 15 13:44
affectedFile.bak.gz
Searching for: fen -> notFound
Looking at: -rw-rw-r-- 1 ewmaint pscop 112 Mar 15 13:49
searchNreplacePairs
Searching for: fen -> notFound
Looking at: -rw-rw-r-- 1 ewmaint pscop
Searching for: fen -> notFound
Looking at: fen is cool
Searching for: fen -> found
743 dgi:/tmp% cat /tmp/file[23]
rw-r-- 1 ewmaint pscop 206 Mar 15 13:44 affectedFile.bak.gz
-rw-rw-r-- 1 ewmaint pscop 112 Mar 15 13:49
searchNreplacePairs
-rw-rw-r-- 1 ewmaint pscop
ton
is cool
rw-r-- 1 ewmaint pscop 206 Mar 15 13:44 affectedFile.bak.gz
-rw-rw-r-- 1 ewmaint pscop 112 Mar 15 13:49
searchNreplacePairs
-rw-rw-r-- 1 ewmaint pscop
ton
744 dgi:/tmp%
Sent via Deja.com http://www.*-*-*.com/
Before you buy.