我有一个让我发疯的 perl 脚本问题。我编写了一个使用 File::Find 模块的脚本,该模块应该从给定的参数目录开始递归地遍历,并对找到的每个 *.txt 文件执行一个函数。我简化了这个问题,只显示主要部分。
为了让它运行并重现我的问题,我们必须创建一个包含两个文件的目录:
fist.txt
每个文件second.txt
只有两行:
cat fist.txt
:
AAA
BBB
cat second.txt
:
AAA
BBB
#!/usr/bin/perl
use File::Find;
$ARGS_NUM = $#ARGV + 1;
if ($ARGS_NUM != 1) {
print "Add start directory as an argument!\n";
exit(-1);
}
my $DEST_DIR =$ARGV[0];
find(\&splitter, $DEST_DIR);
sub splitter {
if (-f $_ && /\.txt$/) {
$DOC_FILE_NAME = $_;
print "processing: $DOC_FILE_NAME\n";
open $DOC_FILE, "<"."$DOC_FILE_NAME" or die "Could not open $DOC_FiLE\n";
print "Entering first WHILE, DOC_FILE = $DOC_FILE\n";
$AAA_FOUND = 0;
$BBB_FOUND = 0;
while(<$DOC_FILE>) {
print "first_while\n";
if (m/^AAA$/i) {
print "FOUND: AAA in $DOC_FILE\n";
$AAA_FOUND = 1;
next;
}
if (m/^BBB$/i) {
print "FOUND: BBB in $DOC_FILE\n";
$BBB_FOUND = 1;
next;
}
}
#################### SECOND WHILE WCHICH FAILS.... #################
$/="";
seek $DOC_FILE,0,0;
$QQQ_FOUND = 0;
print "Entering second WHILE, DOC_FILE = $DOC_FILE\n";
while(<$DOC_FILE>) {
print "second_while\n";
s/\n//g; s/$/\n/; s/^\s*//;
if ($QQQ_FOUND == 1) {
$question_text = $_;
print "question_text = $question_text\n";
last;
}
if (m/^QQQ.*$/i) {
$QQQ_FOUND=1;
}
}
$/ = undef;
print "AAA = $AAA_FOUND\n";
print "BBB = $BBB_FOUND\n";
print "QQQ = $QQQ_FOUND\n";
close $DOC_FILE;
}
}
这是输出:
processing: first.txt
Entering first WHILE, DOC_FILE = GLOB(0x13087e0)
first_while
FOUND: AAA in GLOB(0x13087e0)
first_while
FOUND: BBB in GLOB(0x13087e0)
Entering second WHILE, DOC_FILE = GLOB(0x13087e0)
second_while
AAA = 1
BBB = 1
QQQ = 0
processing: second.txt
Entering first WHILE, DOC_FILE = GLOB(0x13087e0)
first_while
Entering second WHILE, DOC_FILE = GLOB(0x13087e0)
second_while
AAA = 0
BBB = 0
QQQ = 0
编辑:如您所见,第二个循环错过了搜索值 AAA 和 BBB。