using variable in search and replace

S

swamy455

Hi all,
I am trying to search for a string in FILE1 and then split it and then
use the result to search FILE2

#!/usr/bin/perl
print "This is test perl program\n";
open ( FILE1,"</test/file1.pl") or die "cannot open $?:$!";
while (<FILE1>){
$i= s/apple/APPLE/;
#just replacing apple with APPLE
#this works fine
if($i){
$test1=$_;
}
}
close FILE1;
print "test1 =$test1\n";
#this has the the whole line which is of #the form a b

($a,$b)=split(/\s/,$test1,2);
print "b=$b\n";

open (FILE2,"</temp/file2.pl") or die "cannot open $?:$!";
while (<FILE2>){
$i= s/$b/MANGO/e;
# This part doesn't work

print $_;
if($i){
$test2=$_;

}
}
close FILE2;
#print "$test2";
($c,$d)=split(/\s/,$test2,2);
print "d= $d\n";

the contents of file1he
ap878ple mango
1apple me45ango
a4pple mat5ngo
apple mango
a2pple ma43ngo
a4pple mat5ngo

the contents of file2
mandfgo andwefrwehra
maafweewngo andhvwera
mango pineapple
masvffngo anewfwdhra

Main purpose of the code is
given apple I want to search file1 and file2 and find pineapple.
the variable $b doesnt seem to work well in the search.

Thanks in advance.
Ravi
 
G

Gunnar Hjalmarsson

I am trying to search for a string in FILE1 and then split it and then
use the result to search FILE2

#!/usr/bin/perl
print "This is test perl program\n";

print "so of course I enable strictures and warnings:\n";
use strict;
use warnings;
open ( FILE1,"</test/file1.pl") or die "cannot open $?:$!";
while (<FILE1>){
$i= s/apple/APPLE/;
#just replacing apple with APPLE
#this works fine
if($i){
$test1=$_;
}
}
close FILE1;
print "test1 =$test1\n";
#this has the the whole line which is of #the form a b

($a,$b)=split(/\s/,$test1,2);
print "b=$b\n";

Replace that line with

print "b=[$b]\n";

and consider the result.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,701
Latest member
XavierQ83

Latest Threads

Top