in reply to Using expressions in arrays for pattern matching
Presumably the params.txt file doesn't change while you're iterating over the *.RPT files, so you should take that bit out of the loop.
You also say I then want to open each file as well as write to an OUTPUT file (with the same name but a .TXT extension.)
but in your code, you give the output file a .dat suffix. Oh, and you aren't checking the return value of your open for the OUTPUT filehandle.
Make sure that if your @params array contains items with characters that are special in regular expressions that you mean for them to be used as such.
Are you sure that your regular expression for the each @params is correct? You want to match exactly one whitespace character, followed by a single element of the @params array, optional whitespace, then optional numbers? Judging from the heading in your output, you should probably capture the parameter and those optional digits separately. Here's an untested rewrite:
#!/usr/bin/perl use warnings; use strict; open PARAMS, "params.txt" or die "Couldn't open the file. $!"; my @params=<PARAMS>; close PARAMS; my @files = glob("*.RPT"); for my $i (@files) { open INPUT, "$i" or die "Couldn't open the file. $!"; open OUTPUT, ">$i.dat" or die "Couldn't write to $i.dat - $!"; print OUTPUT "$i\n\n"; print OUTPUT " Parameter Value\n"; print OUTPUT "-------------------------\n"; while (<INPUT>) { for my $x (@params) { next unless /\s($x)\s*(\d*)/; print OUTPUT "$1 $2\n"; # probably use printf() here } } close INPUT; close OUTPUT; }
If the things in @params are just words (i.e., no regular expression special characters), you probably want to make a single regular expression out of them ahead of time and rewrite the inner loop like so:
... my $paramre = join '|', @params; ... while (<INPUT>) { next unless /\s($paramre)\s*(\d*)/; print OUTPUT "$1 $2\n"; } ...
Of course, even if they contain regular expression special characters you might want to do this, but be really careful about it. :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Using expressions in arrays for pattern matching
by sauoq (Abbot) on Dec 01, 2003 at 18:54 UTC | |
by duff (Parson) on Dec 01, 2003 at 19:11 UTC |