You're right, some of these lines aren't doing what you think. next immediately breaks out of the current while loop and restarts the loop at the beginning, so the following line is never executed. That means it never tells you that $replace is undefined, so what you're trying to do with it won't work.

In general, when your text is arranged in multi-line chunks, it works best to process it that way rather than line-by-line. You can use the input record separator variable $/ to split your input file on something that ends each chunk. That way you don't have to dance around with saving each line long enough to look at the next line and see if something needs to be done to the previous line before outputting it.

Here's an example of what I'm talking about; you can adjust it to use your input and output files. It reads in each chunk, looks to see if it has the piece you want to copy, and copies it into the other spot if it's there.

#!/usr/bin/env perl use strict; use warnings; $/ = '/Hit_accession>'; while(<DATA>){ if( m{<Hit_def>(.+?) odorant-bin} ){ my $match = $1; s{(<Hit_id>).+?(</Hit_id>)}{$1$match$2}; } print $_; } __DATA__ <Hit_num>6</Hit_num> <Hit_id>gnl|BL_ORD_ID|3665984</Hit_id> <Hit_def>gi|158703516|gb|ABW77886.1| odorant-bin... <Hit_accession>3665984</Hit_accession> <Hit_num>7</Hit_num> <Hit_id>gnl|BL_ORE_ID|3665984</Hit_id> <Hit_def>gi|153326716|gb|ABF88997.2| odorant-bin... <Hit_accession>3665984</Hit_accession>

Aaron B.
Available for small or large Perl jobs; see my home node.


In reply to Re: replace part of a line with part of the following line after if is TRUE by aaron_baugher
in thread replace part of a line with part of the following line after if is TRUE by N311V

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.