Can't call method "text" without a package or object reference

rParvathi Source

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.

perl

Answers

answered 6 months ago Borodin #1

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

comments powered by Disqus