you should have noticed the extra blank line in your ouput, after the "b=mango" -- this is because the split is being told to take everything after the first whitespace character (in this case, everything after "apple ") and assign it to $y, and in this case, "everything" includes the line termination character(s) (LF or CRLF, depending on your OS).($a,$b)=split(/\s/,$test1,2); print "b=$b\n";
When you look for that target word in the second file, "mango" happens to be in the first column, where it is followed by a space character (not LF or CRLF), so $b never matches, the substitution never happens, and nothing gets assigned to $test2.
You can either "chomp" the input from the first file before capturing the string you intend to use later, or else you can do @a = split ' ', $test1; and then use the appropriate element of @a later on.
(Note that using $a and $b for actual data variables is bad, because if you end up using the "sort" function as well, you'll get messed up. But using @a and @b is okay.)
UPDATE: Based on your closing comment:
Main purpose of the code is given apple I want to search file1 and file2 and find pineapple.
I think a simple script for that would be:
use strict; my $target; open( I, "file1" ) or die "file1: $!"; while (<I>) { if ( /^apple\s+(.*)/ ) { $target = $1; # note: .* does not match line terminators last; } } close I; my $found; open( I, "file2" ) or die "file2: $!"; while (<I>) { if ( /^$target\s+(.*)/ ) { $found = $1; last; } } close I; print "found: <<$found>>\n";
In reply to Re: using variable in search and replace
by graff
in thread using variable in search and replace
by ravi1980
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |