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

Hi
I make the perl program to download the image file on the net.

my $imgsrc = 'http://pds11.egloos.com/pmf/200810/15/30/b0039730_48f5ba15f3441_t.jpg';
my $imgdst = '001.png';
my $mech = WWW::Mechanize->new(); # mesh
my $temp = $mech->get($imgsrc);


But this code occur the error message like this.

Error GETing http://pds11.egloos.com/pmf/200810/15/30/b0039730_48f5ba15f3441_t.jpg: Not Found at test.pl line 74

That's because url is wrong.
But I want to handle this error rather than die.
I mean if url is wrong, then pass the url and see next image url, not die.
But I can't find the method on the WWW::Mechanize page.
Please comment it.

Replies are listed 'Best First'.
Re: handling WWW::Mechanize Error GETing
by jeffa (Bishop) on Jan 21, 2009 at 14:30 UTC

    The typical way to tame 3rd party code in Perl is to wrap the "offending" call in eval and check $@ for the "exception"

    my $temp; eval { $temp = $mech->get($imgsrc); } if ($@) { # alert the error }

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      Small (but essential) correction to jeffa's answer: The terminating semi-colon should be outside the eval braces otherwise perl throws a (unhelpful) compilation error. eval { $mech->get($imgsrc) }; if ($@) { # alert the error }

        Hi,

        Using if($@) is unreliable,

        The correct pattern is

        $temp = eval { $mech->get($imgsrc) }; if( not $temp ){ ... }

        But we're using mech so we dont need to store the response in $temp

        So even better

        eval { $mech->get( $imgsrc ); }; if( not $mech->res->is_success ){ ... }

        Or even better

        if( not eval { $mech->get( $imgsrc ); 1 } ){ ... }

        Or simply the generic version , it doesn't rely on $@

        eval { $mech->get( $imgsrc ); 1 } or do { ... };

        For explanation why using if($@) is unreliable see Devel::EvalError -- Reliably detect if and why eval() failed

Re: handling WWW::Mechanize Error GETing
by Corion (Patriarch) on Jan 21, 2009 at 14:31 UTC