I have made a script that fetches the title of a (supposed) web page. The problem arises when I give a big file (which is n't even text/html) to the script. The file gets downloaded (waste of bandwidth) and after downloading it, the script notices it isn't text/html. Here's the script:
#!/usr/bin/perl -w use HTML::TokeParser; use LWP::Simple; use Encode; sub getTitle { my $stream = HTML::TokeParser->new(@_); if(defined $stream->get_tag("title")) { my $title = $stream->get_trimmed_text; return encode_utf8($title); } } my $browser; my $url = $ARGV[0]; BEGIN { use LWP::UserAgent; $browser = LWP::UserAgent->new; $browser->agent("Mozilla/5.0"); $browser->timeout(15); } my $resp = $browser->get($url); die "Error getting $url: ", $resp->status_line, "\n" unless $resp->is_success; die "Not HTML, it's ", $resp->content_type, "\n" unless $resp->content_type eq 'text/html'; if(my $title = getTitle($resp->content_ref)) { print "Title: '$title'\n"; }
What would be the solution for this? I should probably make a limit of some sort, say 32kB, for the get(). This seems to be a common problem, but I haven't found a decent solution. Also, should I worry about the content-encodings of the pages or does encode_utf8() take care of those too? Thanks in advance.

In reply to Fetching titles and error handling by Anonymous Monk

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.