in reply to Working with text files, thinking my issue is with variables inside if loops

Although a few others have posted good information already, I'll toss in my two cents.

And yes, I am aware that I'm not using strict or warnings, and that I should be, but...

Speaking from personal experience, I'd recommend getting into the habit of using these lines of code, which will help you identify problems sooner.

Also, I noticed that you only error checked on just one of the 3 files that you opened, but you didn't print out the $! variable that contains detailed information about why the open command fails. If you add that in every time you open a file, it will help to quickly identify the source of problems if open fails.

Applying the above thoughts along with the stuff from jdporter's and blakew's posts, I'd rewrite your code as the following untested code:

use strict; use warnings; open(FILE,"<messages.txt") or die "Unable to open file 'messages.txt': + $!\n"; open(my $daniel,">Daniel.txt") or die "Unable to open file 'Daniel.txt +': $!\n"; open(my $steffi,">Steffi.txt") or die "Unable to open file 'Steffi.txt +': $!\n"; my $fh = "none"; while (<FILE>) { chomp; if (/^\s*Daniel\s+Lastname\s*$/s) {$fh = $daniel;} if (/^\s*Steffi\s+Lastname\s*$/s) {$fh = $steffi;} if ($fh ne "none") {print $fh $_;} } close($steffi); close($daniel); close(FILE);

Hopefully the code above or from blakew's post will help get you going the right direction.

  • Comment on Re: Working with text files, thinking my issue is with variables inside if loops
  • Download Code

Replies are listed 'Best First'.
Re^2: Working with text files, thinking my issue is with variables inside if loops
by CountZero (Bishop) on May 24, 2011 at 06:53 UTC
    Don't forget to add a "\n" when you print the message to the file! You have chomped the original "\n"!

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      Good catch! Since I usually don't use variables for filehandles in the code that I write, I got a little too focused on the filehandles and overlooked that detail.