oliwiak82
oliwiak82

Reputation: 21

Perl simple loop

Can somebody explain why my loop does not work?

#!/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";

}

This is the error :

# 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.

Upvotes: 2

Views: 133

Answers (1)

William Pursell
William Pursell

Reputation: 212238

$varpages is lexically scoped to the code block:

# Get number of pages and define as var
for my $j (0 .. $#{$res->{pages}}) {
 my $varpages = $res->{pages}[$j];
  print "$varpages\n";
}

The attempt to reference it later references a different variable. If you want $varpages to have global scope, declare it outside the block that assigns to it. For example:

my $varpages;
# Get number of pages and define as var
for my $j (0 .. $#{$res->{pages}}) {
  $varpages = $res->{pages}[$j];
  print "$varpages\n";
}

Upvotes: 5

Related Questions