in reply to using variable in search and replace
Hi ravi1980,
Welcome to the Monastery, I think this is your first post, please take a look at How (Not) To Ask A Question. Add the code tags for coding part. Your question is not clear and unless your requirement is clear, you cannot get correct answer, you ll get answers only in assumption.
Also use strict and warnings for your coding. In your coding, you are replacing 'apple' with 'APPLE' in which you have used '=' instead of '=~' for regular expressions match. You are using 'e' option modifer unnecessarily in the regular expressions. Your variables are not declared properly in the coding. Take a look at perlre.
Here is my try, if i understood your question correctly,
use strict; use warnings; print "This is test perl program\n"; open ( FILE1,"<1.txt") or die "cannot open $?:$!"; my ($test1, $test2); while (<FILE1>){ chomp ($_); my ($i) = $_ =~ s/apple/APPLE/; #just replacing apple with APPLE #this works fine if($i) { $test1=$_; } } close FILE1; print "test1 = $test1\n\n"; #this has the the whole line which is of #the form a b my ($a,$b)=split(/\s/,$test1,2); print "b = $b\n"; open (FILE2, "<2.txt") or die "cannot open $?:$!"; while (<FILE2>){ chomp($_); my ($i) = $_ =~ s/$b/MANGO/; if($i) { $test2=$_; } } close FILE2; print "\ntest2 = $test2\n\n"; my ($c,$d)=split(/\s/,$test2, 2); print "d = $d\n"; outputs: -------- This is test perl program test1 = APPLE mango b = mango test2 = MANGO pineapple d = pineapple
Also avoid using $a and $b as variable names because of their use by sort function.
update: Added last para, thanks to wfsp :)
Prasad
|
|---|