Is that second seek() really going to work on windows? Suppose on windows you have these lines in a text file:

22\r\n 4444\r\n 333\r\n

After reading the second line, I think tell() will report the file position as 10:

01 2 34567 8 90 22\r\n4444\r\n

And the length of the second line as reported by length($line) in your code will be 5: when reading a line from a file, perl automatically converts the actual newline found in the file(in this case \r\n) to \n, so $line will be assigned "4444\n", and length($line) will be 5. So $pos = 10 - 5 = 5. Then seeking to position 5 in the file will land you here:

22\r\n 4444\r\n ^ file pointer

...which is not the start of the line. Can anyone test that on windows?

Using seek() to move to the beginning or end of the file will work because those are absolute positions--but doing a relative seek() won't work because counting the length of a line with a perl program does not give you the actual length of the line in the file. To do relative seeks, you need to turn off the automatic newline conversions that occur while reading a file by using something like binmode().


In reply to Re^4: How do I move two lines up in a file using perl by 7stud
in thread How do I move two lines up in a file using perl by sabertooth

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.