我正在开发一个小的perl程序,它将打开一个站点并搜索单词Hail Reports,然后返回给我信息。我对perl非常陌生,因此其中一些问题可能很容易修复。首先,我的代码显示我使用的是一个单一化值。这是我所拥有的
#!/usr/bin/perl -w
use LWP::Simple;
my $html = get("http://www.spc.noaa.gov/climo/reports/last3hours.html")
or die "Could not fetch NWS page.";
$html =~ m{Hail Reports} || die;
my $hail = $1;
print "$hail\n";其次,我认为正则表达式是做我想做的事情的最简单的方法,但我不确定我是否能用它们做这件事。我希望我的程序搜索单词Hail Reports,并将Hails Reports和Wind Reports之间的信息返回给我。使用正则表达式可以做到这一点吗?还是应该使用不同的方法?下面是我希望它发回的网页源代码片段
<tr><th colspan="8">Hail Reports (<a href="last3hours_hail.csv">CSV</a>) (<a href="last3hours_raw_hail.csv">Raw Hail CSV</a>)(<a href="/faq/#6.10">?</a>)</th></tr>
#The Data here will change throughout the day so normally there will be more info.
<tr><td colspan="8" class="highlight" align="center">No reports received</td></tr>
<tr><th colspan="8">Wind Reports (<a href="last3hours_wind.csv">CSV</a>) (<a href="last3hours_raw_wind.csv">Raw Wind CSV</a>)(<a href="/faq/#6.10">?</a>)</th></tr> 发布于 2010-07-03 03:56:45
您在$1中没有捕获到任何内容,因为您的正则表达式都没有包含在括号中。下面的方法对我很有效。
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
my $html = get("http://www.spc.noaa.gov/climo/reports/last3hours.html")
or die "Could not fetch NWS page.";
$html =~ m{Hail Reports(.*)Wind Reports}s || die; #Parentheses indicate capture group
my $hail = $1; # $1 contains whatever matched in the (.*) part of above regex
print "$hail\n";发布于 2010-07-03 04:03:32
未初始化值警告来自$1 --它没有在任何地方定义或设置。
对于行级而不是字节级的"between“,你可以使用:
for (split(/\n/, $html)) {
print if (/Hail Reports/ .. /Wind Reports/ and !/(?:Hail|Wind) Reports/);
}发布于 2010-07-03 08:48:15
使用单行和多行匹配。另外,它只会选择文本之间的第一个匹配项,这比贪婪要快一点。
#!/usr/bin/perl -w
use strict;
use LWP::Simple;
sub main{
my $html = get("http://www.spc.noaa.gov/climo/reports/last3hours.html")
or die "Could not fetch NWS page.";
# match single and multiple lines + not greedy
my ($hail, $between, $wind) = $html =~ m/(Hail Reports)(.*?)(Wind Reports)/sm
or die "No Hail/Wind Reports";
print qq{
Hail: $hail
Wind: $wind
Between Text: $between
};
}
main();https://stackoverflow.com/questions/3168514
复制相似问题