Steffi has asked for the wisdom of the Perl Monks concerning the following question:
Ok, so here's what I'm trying to do. I have a .txt file of a messaging history going back and forth between myself and another person. Throughout the file, it has one of our names, then a line break, then what we said (sometimes multiple paragraphs), etc. (Sometimes the same person said something twice in a row, so the name appears again.) What I want to do is have my perl script go through this file and split it up into two files: one of things I said, one of things my friend said.
What I thought I could do is read in the whole file into an array, line by line, and then whenever the next line is "Steffi Lastname" or "Daniel Lastname" tell it that it should be writing to that person's output file.
I'm pasting my code (which isn't working) below. I've figured out that it isn't updating my $printto variable, so in the last two if loops it isn't matching with "Daniel" or "Steffi." (I tried initizing the $printto to "Daniel" and then it just copied the whole messages.txt file into Daniel.txt and didn't put anything into Steffi.txt.) What am I doing wrong?
(And yes, I am aware that I'm not using strict or warnings, and that I should be, but if that can be overlooked for this particular script I would rather not. I am very new to Perl and don't know how to make any of it work at all while using strict and warnings.)
open (FILE, "<messages.txt") or die ("Name the input file 'messages.tx +t' and make sure it is in the correct directory."); open (DANIEL, ">Daniel.txt"); open (STEFFI, ">Steffi.txt"); @lines = <FILE>; #reads the file into an array, with each element in t +he array containing one line $numberOfLines = @lines; #number of elements in the input array $lineNumber = 0; $printto; while ($lineNumber < $numberOfLines) { if ($lines[$lineNumber] eq "Daniel Lastname") { $printto = "Daniel"; } if ($lines[$lineNumber] eq "Steffi Lastname") { $printto = "Steffi"; } if ($printto eq "Daniel") { print DANIEL "$lines[$lineNumber]"; $lineNumber++; } if ($printto eq "Steffi") { print STEFFI "$lines[$lineNumber]"; $lineNumber++; } } close(DANIEL); close(STEFFI);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Working with text files, thinking my issue is with variables inside if loops
by jdporter (Paladin) on May 24, 2011 at 01:11 UTC | |
|
Re: Working with text files, thinking my issue is with variables inside if loops
by dasgar (Priest) on May 24, 2011 at 05:30 UTC | |
by CountZero (Bishop) on May 24, 2011 at 06:53 UTC | |
by dasgar (Priest) on May 24, 2011 at 13:29 UTC | |
|
Re: Working with text files, thinking my issue is with variables inside if loops
by blakew (Monk) on May 24, 2011 at 03:05 UTC | |
by holli (Abbot) on May 24, 2011 at 07:56 UTC |