Now I think I understand better, thanks.

The idea of changing the record separator to something else I borrowed from another thread on the list archives, which dealt with a similar problem to mine. I have large text files that contain multi-line, multi-paragraph sections that pertain to a variety of patients. I separated them with ***. I thought as my first exercise in perl, I would try to learn how to extract from those files all the sections that pertain to a particular patient, and print them to the screen. I couldn't think how to do it by walking through the file line-by-line. So that thread about sections and separators really helped. With your suggestions, and a small test input file, it looks like it is working.

I thought the * character needed a backslash to be taken literally. But I guess that's only in regular expressions? I was confused about that.

--Chris

Chas Owens wrote:
On 6/3/07, Ryan <[EMAIL PROTECTED]> wrote:
snip
open F, "JunkTestText.txt";
local $/ = "\*\*\*";
my @sections = <F>;
close F;
snip
When executed, it runs up to and including asking me for input from the
terminal.  When I enter a value for $patient (a 7-digit number) and
press enter, nothing happens.  The cursor goes down to the next line and
just waits.
snip

The Problem is in that section of code.  You did the right thing using
local to limit the scope of $/, but failed to do the other necessary
thing: add a block around the code to cause it to revert back.  This
being Perl there are several solutions.  Here are few in order of my
preference.

#!/usr/bin/perl

use strict;
use warnings;

print "use do to make the three steps into one\n";
my @sections1 = do {
       open my $file, '<', 'JunkTestText.txt';
       local $/ = '***';
       <$file>;
};

print map { "[$_]\n" } @sections1;

print "use a bare block to limit the scope\n";
my @sections2;
{
       open my $file, '<', 'JunkTestText.txt';
       local $/ = '***';
       @sections2 = <$file>;
}

print map { "[$_]\n" } @sections2;

print "save to old value of \$/ and put it back\n";
my $old_in_sep = $/;
$/ = '***';
open my $file, '<', 'JunkTestText.txt';
my @sections3 = <$file>;
#this was not necessary before because
#the file handle closes when it goes
#out of scope
close $file;
$/ = $old_in_sep;

print map { "[$_]\n" } @sections3;


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to