The regex approach needs to look for the "From:" and "Subject:" (and other field labels) only when they appear at the beginning of a line, and it can stop reading input as soon as all the desired fields are found.
Note the regex uses the initial anchor character (^) and non-capturing grouping parens. (You could just as well use the simpler capturing parens, without the "?:" -- this would add a slight bit of extra processing, but not enough to worry about here.)my @fields = qw/From: Subject:/; # you can add more if/when you want my $field_regex = join( "|", @fields ); my @field_lines; while (<$fh>) { push( @field_lines, $_ ) if ( /^(?:$field_regex) / ); last if @field_lines == @fields; } push @field_lines, ""; print join( "\n", sort @field_lines );
(updated to include parens around the args for the first "push" call, just because I like using parens around function args)
In reply to Re: Matching multiple patterns with regex
by graff
in thread Matching multiple patterns with regex
by Tiarcon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |