Hi Monks!, I've got a script where I parse several txt files that contain several urls and extract ones that only contain specific words. Everything works fine but the problem that I have is that I'm opening a fh for each file and sometimes I don't find what I'm looking for and write nothing and create a 1 byte file that I don't need.
I can't seem to figure out a way to do not write the file if there's nothing to write. Here's my codemy $calls_dir2 = 'Bing/1Parsed/Html'; my $parsed_dir = 'Bing/1Parsed/Html2'; open( my $fh2, '<', 'parse1.txt' ) or die $!; chomp( my @parse_terms1 = <$fh2> ); close($fh2); open( $fh2, '<', 'parse2.txt' ) or die $!; for my $parse1 (@parse_terms1) { seek( $fh2, 0, 0 ); while ( my $parse2 = <$fh2> ) { chomp($parse2); print "$parse1 $parse2\n"; my $wanted = $parse1 . $parse2; my @files = glob "$calls_dir2/*.txt"; printf "Got %d files\n", scalar @files; for my $file (@files) { open my $in_fh, '<', $file; my $basename = fileparse($file); my ($prefix) = $basename =~ /^(.{9})/; my $rnumber = rand(1999); print $prefix, "\n"; my @matches; while (<$in_fh>) { push @matches, $_ if /^.*?(?:\b|_)$parse1(?:\b|_). +*?(?:\b|_)$parse2(?:\b|_).*?$/m; } make_path($parsed_dir); open my $out_fh, '>', "$parsed_dir/${basename}.$wanted.$rnumber.txt"; print $out_fh $_ for @matches; print $out_fh "\n"; close $out_fh;
In reply to Don't write to a file if there's no data by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |