Here's a brute-force way of doing it:

use warnings; use strict; my $matching_line_loc = 0; my $matching_line = ''; open (TEST_FILE, "<test.dat") or die "Couldn't open test.dat: $!\n"; while (<TEST_FILE>) { if (/333/) { #remember matching line and line number $matching_line = $_; $matching_line_loc = $.; last; } } close TEST_FILE; if ($matching_line) { #don't bother with rest if no match! open (TEST_FILE, "<test.dat") or die "Couldn't open test.dat: $!\n"; open (TMP_FILE, ">test.tmp") or die "Couldn't open/create test.tmp: $!\n"; #print the matching line first print TMP_FILE $matching_line; #print everything BUT the matching line while (<TEST_FILE>) { print TMP_FILE $_ unless $. == $matching_line_loc; } close TMP_FILE; close TEST_FILE; #remove original file and rename rearranged file unlink "test.dat" or die "couldn't remove test.dat: $!\n"; rename "test.tmp", "test.dat"; }

Note that this way (and others above) avoids the classic problem of 'slurping' the whole file into memory since it only deals with single lines at a time. Slurping would be pretty bad with a 60 meg file (though it would probably still work.)

This method also assumes that there will only every be one matching line.

Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"

In reply to Re: Swaping a record in a File by Art_XIV
in thread Swaping a record in a File by ganeshm69

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.