Search code examples
perlmojolicious

Can't call method "headers" on an undefined value at search.pl line 10


#!/usr/bin/perl
use Mojo::Base -strict;
use Mojo::DOM;
use Mojo::Util qw(decode);
use Mojo::UserAgent;
my $uri = 'http://efremova.info/word/statja.html';
my $sel = 'td#centerCnt ol li';
my $charset = 'windows-1251';
my $tx = Mojo::UserAgent->new()->get($uri);
my $res->headers->content_type("text/html; charset=$charset");
my $dom = $res->dom;
my $el = $dom->at($sel) or die "selector $sel not found";
$el->find('span.nobr')->each(sub { $_->replace($_->text) });
my $text = $el->text;
binmode(STDOUT, ':encoding(UTF-8)');

get error: Can't call method "headers" on an undefined value at search.pl line 10.

what should I do?

Thanks a lot


Solution

  • You forget that, you need to first get res from tx.

    my $tx = Mojo::UserAgent->new()->get($uri);
    
    my $res = $tx->res;
    
    $res->headers->content_type("text/html; charset=$charset");
    my $dom = $res->dom;