in reply to How to use REGEX Match Variable from one 'While' String in Another 'While' String

In addition to the changes suggested by AnonyMonk above, I find it is wise to capture regex 'capture' variables and get them nailed down as soon as possible. This is because the evaluation of any further regex will probably cause the contents of these variables to... well, vary. (You say, "But I'm not using any other regex and never will." Famous Last Words. Nail them down. And, in fact, you do have another regex, the one in the second, nested while-loop. If you were ever to add a statement after the second while-loop that made reference to the  $1 $2 $3 $n   capture variables expecting that they would retain the values they had after execution of the first regex, you would be unpleasantly surprised. Nail them down.)

Maybe something like this. (Since you don't seem to use  $1 anywhere, I leave it out of account.) (Note the  /g modifier on the  m//xmsg regexes.) (Untested)

my $pkt_file = ...; my $dat_file = ...; ... open (my $fh_pkt, '<', $pkt_file) or die "ERROR Opening $pkt_file (Err +or = $!)\n"; ... while (defined(my $line_in = <$fh_pkt>)) { if (my ($pkt) = $line_in =~ m{ \w+ \s+ (\w+) }xmsg) { my $out_file = "${pkt}_tlmval.txt"; open (my $fh_out, '>>', $out_file) or die "ERROR Opening '$out +_file' (ERROR = $!)\n"; ... open (my $fh_data, '<', $dat_file) or die "..."; while (defined(my $line_in = <$fh_data>)) { if (my ($foo, $bar) = $line_in =~ m{ \Q$pkt\E \s+ (\w+) \s ++ = \s+ (\d+) }xmsg) { print $fh_out "check '$pkt' '$foo' vs '$bar'\n"; } } } }

Note that the  $line_in lexical variable in the nested while-loop is guaranteed to be completely separate and isolated from the lexical of the same name in the outer loop. Even so, I think I would prefer to use different names for these two variables just for the sake of self-documentation and maintainability.

Replies are listed 'Best First'.
Re^2: How to use REGEX Match Variable from one 'While' String in Another 'While' String
by GoldfishOfDoom (Initiate) on May 07, 2014 at 18:44 UTC

    AnomalousMonk,

    Thank you for the additional comments. I'm always looking on ways to improve and make things flexible for any 'unexpected' changes or additions. This was extremely helpful in cleaning up my script.

    I appreciate you taking the time to respond.