문제

I have a code snippet like the following:

use strict;
use warnings;

# file names to search for
open(my $files,  "<",  "fileList.txt") or die "Can't open fileList.txt: $!";

my $flag = 0;
while (<$files>) {
    print "File loop: $_\n";

    open(my $search,  "<",  "searchMe.txt") or die "Can't open searchMe.txt: $!";

    $flag = 0;
    while (<$search>){
        print "Search loop: $_\n";
    }
}

fileList.txt contains one line: "CheckFilesFunctions.pm"

searchMe.txt contains one line: abc

The output here is

File loop: CheckFilesFunctions.pm
Search loop: abc

However. when I change the search loop to the following

while (<$search> && !$flag){

Suddenly the search loop starts printing

Search loop: CheckFilesFunctions.pm

Why does the scope of $_ change here?

도움이 되었습니까?

해결책

while (<filehandle>) is convenient shorthand for while (defined( $_ = <filehandle> )); if you have a more complicated expression to test, you need to explicitly include the full thing:

while ( defined( $_ = <$search> ) && ! $flag ) {

though I would suggest explicitly using readline (<> can mean either readline or glob, depending on the argument; I prefer to use those directly) and using a lexical variable:

while ( defined( my $line = readline $search ) && ! $flag ) {

Alternatively, you could break out of the loop instead of modifying the condition:

while (<$search>) {
    ...
    if (...) {
        last;

Though looking at your code, you probably want to be reading the search file just once into an array before the file loop, and just looping over that array.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top