-1

The following is my code

use warnings;
use LWP::Simple;
use WWW::Mechanize;
use WWW::Mechanize::Link;


my $mech = new  WWW::Mechanize();
my $link = new  WWW::Mechanize::Link();

my $file = 'source1.txt';
my $filename = 'links2.txt';

open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {
 $link = grep(/<a.*href=.*>/,$line);
   print $fh $link->text;

}
close $fh;

when I try to run this I get the error Can't call method "text" without a package or object reference.

rParvathi
  • 1,939
  • 2
  • 16
  • 21
  • 5
    *Always* `use strict;`! – Biffen Feb 14 '18 at 12:55
  • 6
    `grep` doesn’t do what you think it does, and you’re [parsing HTML with regex, which is a bad idea](https://stackoverflow.com/a/1732454/418066). The immediate error, however, is with `$link->text`; consider what `$link` is here. – Biffen Feb 14 '18 at 12:58
  • 3
    Why do you have LWP::Simple and WWW::Mechanize and use neither? – simbabque Feb 14 '18 at 13:04

1 Answers1

5

In scalar context, grep returns the number of items in the list that "match" the criterion. So, because there is only one item in your list, your statement

$link = grep( /<a.*href=.*>/, $line )

will set $link to either 1 or 0 according to whether $line matches the regex /<a.*href=.*>/

Then you have

print $fh $link->text

which calls either 1->text or 0-text, neither of which make sense

Borodin
  • 126,100
  • 9
  • 70
  • 144