我是Perl新手,有一个关于语法的问题。我收到了这段代码,用于解析包含特定信息的文件。我想知道子例程get_number的if (/DID/)部分在做什么?这是在利用正则表达式吗?我不太确定,因为正则表达式匹配看起来像$_ =~ /some expression/。最后,get_number子例程中的while循环是必要的吗?
#!/usr/bin/env perl
use Scalar::Util qw/ looks_like_number /;
use WWW::Mechanize;
# store the name of all the OCR file names in an array
my @file_list=qw{
blah.txt
};
# set the scalar index to zero
my $file_index=0;
# open the file titled 'outputfile.txt' and write to it
# (or indicate that the file can't be opened)
open(OUT_FILE, '>', 'outputfile.txt')
or die "Can't open output file\n";
while($file_index < 1){
# open the OCR file and store it in the filehandle IN_FILE
open(IN_FILE, '<', "$file_list[$file_index]")
or die "Can't read source file!\n";
print "Processing file $file_list[$file_index]\n";
while(<IN_FILE>){
my $citing_pat=get_number();
get_country($citing_pat);
}
$file_index=$file_index+1;
}
close IN_FILE;
close OUT_FILE;get_number的定义如下。
sub get_number {
while(<IN_FILE>){
if(/DID/){
my @fields=split / /;
chomp($fields[3]);
if($fields[3] !~ /\D/){
return $fields[3];
}
}
}
}发布于 2011-07-02 19:51:05
在这种情况下,默认情况下,if (/DID/)会搜索$_变量,因此它是正确的。然而,它是一个相当松散的正则表达式。
sub中的while循环可能是必要的,这取决于您的输入是什么样子。您应该知道,两个while循环将导致某些行被完全跳过。
主程序中的while循环将占用一行代码,并且不对其执行任何操作。基本上,这意味着文件中的第一行,以及紧跟在匹配行之后的每一行(例如,包含"DID“的行和第四个字段是一个数字)也将被丢弃。
为了正确回答这个问题,我们需要查看输入文件。
这段代码有许多问题,如果它能像预期的那样工作,这可能是由于健康的运气。
下面是代码的一个经过清理的版本。我把模块放在里面,因为我不知道它们是否在其他地方使用。我还保留了输出文件,因为它可能会在您没有显示的地方使用。这段代码不会尝试为get_country使用未定义的值,如果找不到合适的数字,也不会执行任何操作。
use warnings;
use strict;
use Scalar::Util qw/ looks_like_number /;
use WWW::Mechanize;
my @file_list=qw{ blah.txt };
open(my $outfile, '>', 'outputfile.txt') or die "Can't open output file: $!";
for my $file (@file_list) {
open(my $in_file, '<', $file) or die "Can't read source file: $!";
print "Processing file $file\n";
while (my $citing_pat = get_number($in_file)) {
get_country($citing_pat);
}
}
close $out_file;
sub get_number {
my $fh = shift;
while(<$fh>) {
if (/DID/) {
my $field = (split)[3];
if($field =~ /^\d+$/){
return $field;
}
}
}
return undef;
}发布于 2011-07-02 14:47:43
Perl有一个variable $_,它在某种程度上是很多东西的默认转储场所。
在get_number中,while(<IN_FILE>){将一行读入$_,下一行检查$_是否与正则表达式DID匹配。
在没有给定参数的情况下,也可以在$_上运行的chomp;也很常见。
https://stackoverflow.com/questions/6555525
复制相似问题