When you did this:
($a,$b)=split(/\s/,$test1,2); print "b=$b\n";
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).

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.