2

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.
2
  • What value do you expect $varpages to have after leaving the first loop? Commented Dec 8, 2012 at 18:16
  • I want the value scraped from: process "div.something", 'pages[]' => '@rel'; Commented Dec 8, 2012 at 19:09

1 Answer 1

5

$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";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hello, So I defined the $varpages var before the loop, and now I have the following error: Use of uninitialized value $varpages in numeric le (<=) at 6
That would certainly happen if $#{$res->{pages} is zero. Try initializing: my $varpages = 0;
Did you remove the 'my' from 'my $varpages' inside the for-loop, as William suggested?
Ups, I didn't. That was the problem. Thanks for this and for William also for pointing the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.