in reply to how to store link array in for loop with WWW::Mechanize

You should add use strict; and use warnings; at the top of your scripts. This will print error or warning messages that may seem bothersome, but will actually help you find most of your mistakes. You can even add use diagnostics; for clearer messages. See strict and warnings;

I'm telling you this because it would have helped in your case, with strict you will have to declare your variables (ie: tell perl what you need), and perl will be able to tell when you have misused or mispelled a variable most of the time. In your case, @link{$cnt} means a list of 1 element from the hash %link (@ means several elements, and { } means it's taken from a hash). If you do: $link[$cnt] = $mech->find_all_links(tag => "a", class => "foo") or die "can't find link"; The $ at the beginning of $link[$cnt] means single element and [ ] that you are taking it from the array (@link).

But since $cnt starts with the value 1, and arrays start at 0, you will have nothing at $array[0], so what you want to do is push your link at the end of @link.:

use strict; use warnings; use Data::Dumper; use WWW::Mechanize; my @link; for my $cnt (1..3) { my $url = "http://www.foo.com/p/$cnt"; my $mech = WWW::Mechanize->new(); $mech->get($url) or die "no such url"; push @link, $mech->find_all_links(tag => "a", class => "foo") or di +e "can't find link"; } # Do something with @link here, after the loop is done print Dumper \@link; # Show the content of @link
I haven't corrected everything in your code, but this should allow you to move forward. Don't hesitate to come back and ask more questions for your next steps ;-).

Replies are listed 'Best First'.
Re^2: how to store link array in for loop with WWW::Mechanize
by Eily (Monsignor) on Nov 06, 2014 at 16:20 UTC

    yitzchak on the CB made me realize I may have misunderstood what you were doing:

    use strict; use warnings; use Data::Dumper; use WWW::Mechanize; my %links; for my $cnt (1..3) { my $url = "http://www.foo.com/p/$cnt"; my $mech = WWW::Mechanize->new(); $mech->get($url) or die "no such url"; my @link = $mech->find_all_links(tag => "a", class => "foo") or die + "can't find link"; $links{$cnt} = \@link; } # Do something with @link here, after the loop is done print Dumper \%link; # Show the content of %link
    The output of Data::Dumper should allow you to find which version suits your needs the best.

      Eily..thanks for your response..both solution work perfect for me.. i just need to stored the link from $mech->find_all_links(tag=> "a", class =>"foo")
      into 1 array after its loop for three times with different $cnt url. thanks a lot..