Hi, 

Michael Alipio <[EMAIL PROTECTED]> asked:
> I've been thinking about this for quite some time now.
> Suppose I have a text file ("mypet.log" that contains:
> 
> dog
> pig
> cat
> 
> Then I have another text file and I want to read it line by 
> line and extract each line that has those contained in the 
> first file. Sort of like running while inside while.
> 
> "myallpetlogs" contains:
> 
> blabla dog blah
> blabla cat blah
> blabla dog blah
> blabla pig blah
> blabla cat blah
> blabla pig blah
> 
> 
> Now, the goal is to have 3 files which contains all extracted 
> lines in "myallpetlogs"

Assuming that you don't have too many log extracts to create, the easy
way would be to read in mypet.log first and open a new logfile for
each entry using a scalar as the filehandle. That scalar can be stored
in a hash using the pet name as a key.

When reading the logfile you determine the pet name using a regular
expression and write the line to the pets logfile if you have a match.

Untested code idea below:

open( IN, '<', $petfile ) or die "Can't open $petfile: $!";

my %log;

while( my $pet = <IN> ){
  chomp( $pet );
  open( my $fh, '>', "$pet.log" ) or die "Can't open $pet.log: $!";
  $log{$pet} = $fh; 
}

close( IN );

my $re = '^\S+\s+(' . join( '|', keys %log ). ')';

open( IN, '<', $logfile ) or die "Can't open $logfile: $!";

while( my $line = <IN> ){
  if( $line =~ m/$re/ ){
    print $log{$1} $line;
  }
}

__END__

HTH,
Thomas

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


Reply via email to