有人可以解释为什么我的循环不起作用吗?
#!/usr/bin/perl -w
use warnings;
use strict;
use URI;
use Web::Scraper;
my $url = "http://example.com";
# prepare data
my $scrapedata = scraper {
process "div.something", 'pages[]' => '@rel';
};
# scrape the data
my $res = $scrapedata->scrape(URI->new($url));
# Get number of pages and define as var
for my $j (0 .. $#{$res->{pages}}) {
my $varpages = $res->{pages}[$j];
print "$varpages\n";
}
for ( my $count = 2; $count <= $varpages; $count++) {
print "$varpages\n";
print "$count\n";
}
这是错误:
# perl oli
Global symbol "$varpages" requires explicit package name at oli line 25.
Global symbol "$varpages" requires explicit package name at oli line 27.
Execution of oli aborted due to compilation errors.
答案 0 :(得分:6)
$varpages
的词法范围是代码块:
# Get number of pages and define as var
for my $j (0 .. $#{$res->{pages}}) {
my $varpages = $res->{pages}[$j];
print "$varpages\n";
}
稍后引用它的尝试引用了另一个变量。如果希望$varpages
具有全局范围,请在分配给它的块之外声明它。例如:
my $varpages;
# Get number of pages and define as var
for my $j (0 .. $#{$res->{pages}}) {
$varpages = $res->{pages}[$j];
print "$varpages\n";
}