CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [Kenosis] Copying a file and modifying line order output: Edit Log



Laurent_R
Veteran / Moderator

Mar 23, 2013, 3:15 PM


Views: 658
Re: [Kenosis] Copying a file and modifying line order output

Hi Kenosis,

your script will work on the data sample that has been given as an example, but I don't think that it fits the description of the problem provided by the OP, which said that lines located between an 'nx00' and an 'm6' line have to be relocated after the 'm6 line. In your script, your are not testing anywhere for the 'nx00' line. Also, your assumption about a line containing non-white characters or not is purely based onthe example, but not on the OP's description of the problem.

Chris Charley's proposal did address the OP's requirement.

I had given some clues to the OP, hoping that she or he would develop something by herself or himself, but since complete solutions have been provided, I might just give mine. This is my quick (and very quickly tested) solution, using a flag ($bufferize) rather than nested loops:


Code
my ($bufferize, $buffer); 
while (<DATA>) {
$bufferize = 1 if /^n\d+00/;
if (/^m6/) {
print $_, $buffer;
$buffer = "";
$bufferize = 0;
next;
}
$buffer .= $_ and next if $bufferize;
print;
}
__DATA__
text0
n700
text 1
text 2
m6_foobar
n400
text3_3
text 4
m6
n800
text 5
text 6
m6


Output:

Code
$ perl  relocate.pl 
text0
m6_foobar
n700
text 1
text 2
m6
n400
text3_3
text 4
m6
n800
text 5
text 6


An additional comment, probably due from the fact that I am working most of the time with files having tens of gigabytes, is that I usually avoid as much as possible to slurp entire files into memory, prefering progressive iteration using almost no memory.

(Of course, this is assuming that sections between an 'nx00' and an 'm6' line are usually relatively short, say a few lines or a few dozens lines, but never tens of millions of lines, otherwise my program might also use a lot of memory, or more complex solutions using for example tied arrays or temporary files.)


(This post was edited by Laurent_R on Mar 23, 2013, 3:29 PM)


Edit Log:
Post edited by Laurent_R (Veteran) on Mar 23, 2013, 3:29 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives