SergioQ has asked for the wisdom of the Perl Monks concerning the following question:

Hello Perl Monks, My usage of Perl has been light, I've never studied it. If I needed to do something I looked how to do that specific task and moved on. But I've hit a hurdle with WWW::Mechanize::Link. I have no problem with the beginning part:
my $mech = WWW::Mechanize->new(); $mech->get( $url ); my @links = $mech->links(); print Dumper (@links);
And with the Dumper I can see all the data in there, including the parts I want (i.e. specific links). What I cannot figure out how to do is to cast those arrays in @links into individual WWW::Mechanize::Link objects and loop through them. I've tried nested foreach loops, but in the end I just come up with a mess. Each new array just has more arrays, and sometimes a hash reference that I can't dereference. I figure that there must be a proper way. Any hints would be appreciated. Thank you

Replies are listed 'Best First'.
Re: How to properly go through a WWW::Mechanize::Link object?
by Corion (Patriarch) on Apr 23, 2020 at 06:14 UTC

    Have you looked at WWW::Mechanize::Link?

    You have the list of links in your array @links. To get at the first link, you can use $links[0].

    my $mech = WWW::Mechanize->new(); $mech->get( $url ); my @links = $mech->links(); print sprintf "I have %d links\n", 0+@links; for my $link (@links) { print "One link points to " . $link->url; print "\n"; };
Re: How to properly go through a WWW::Mechanize::Link object?
by Your Mother (Archbishop) on Apr 23, 2020 at 07:28 UTC

    What Corion said. The @links are WWW::Mechanize::Link objects already–

    use WWW::Mechanize; my $mech = WWW::Mechanize->new( autocheck => 0 ); $mech->get("https://perlmonks.org/?node=Recently+Active+Threads"); for my $link ( $mech->links ) { printf "* %s\n -> %s\n", $link->text, $link->url_abs; }

      First off, thank you. But this opens something that I've missed in Perl.

      What I was doing was:

      print "name\t\t$link->name\n";

      Which gave me:

      name WWW::Mechanize::Link=ARRAY(0x55bbd8e7d100)->name

      So what am I not understanding? Why does Perl not interpret this?

Re: How to properly go through a WWW::Mechanize::Link object?
by marto (Cardinal) on Apr 23, 2020 at 07:32 UTC
Re: How to properly go through a WWW::Mechanize::Link object?
by choroba (Cardinal) on Apr 23, 2020 at 13:54 UTC
    I usually don't want all the links, but only specific ones. WWW::Mechanize has a method for that:
    my $links = $mech->find_link(text_regex => qr/Read more/, url_regex => + qr{domain\.com} ); for my $link (@$links) { ...

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]