【发布时间】:2015-09-01 03:08:41
【问题描述】:
我要做的是在哈希中检索键值对的键,因为我从正在读取的文件中拥有的只是一个值。
代码产生如下内容:
12345welcome.html
这部分的代码是:
my %bugs;
my $bug;
open(FH, '-|', "lynx -dump '$queryurl'") or die "Could not lynx $queryurl: $!";
while (<FH>)
{
if (/<bz:id[^>]*>([^<]*)</)
{
$bug = $1;
}
if (/<bz:url[^>]*>([^<]*)</)
{
my $url = $1;
$bugs{$url} = $bug;
$bug = undef;
}
}
close(FH);
# for debugging purposes
foreach my $bug (keys %bugs)
{
print "$bugs{$bug} $bug\n";
}
exit;
然后,在名为 bad.txt 的文件中的其他位置,我得到如下输出:
Documents that failed:
daerror 6 0 6 welcome.html
读取这个文件的代码是:
my $badfile = "$dir/bad.txt";
open(FH, "<$badfile") || die "Can not open $badfile: $!";
# ignore first line
<FH>;
while (<FH>)
{
chomp;
if (!/^([^ ]+) [^ ]+ [^ ]+ [^ ]+ ([^ ]+) [^ ]+$/)
{
die "Invalid line $_ in $badfile\n";
}
my $type = $1;
my $testdoc = $2;
}
但我已经使用正则表达式从中提取了文件名。
【问题讨论】:
-
[^ ]+ 也可以写成 \S+ 你也可以使用
m并将 $type 和 $testdoc 设置在一行上。my($type,$testdoc) = $_ =~ m/^(\S+) \S+ \S+ \S+ (\S+) \S+$/; die "Invalid line $_ in $badfiles\n" unless defined $type && defined $testdoc;.