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 ;-).


In reply to Re: how to store link array in for loop with WWW::Mechanize by Eily
in thread how to store link array in for loop with WWW::Mechanize by haiihh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.