Reputation: 2076
I am trying to extract the domain part of a URL and I want to cover the case where the input is invalid.
use strict;
use warnings;
use URI;
use Data::Dumper;
my $url = URI->new( "garbled" );
# my $url = URI->new( "http://www.google.com/" ); # this works
# print Dumper $url;
print $url->host if defined($url->host) ;
Gives Can't locate object method "host" via package "URI::_generic" at
How can check if the URL was parsed correctly?
Upvotes: 2
Views: 272
Reputation: 118605
For the general case you can use UNIVERSAL::can
if (ref($url) && $url->can("host")) { ... }
or exception handling
eval { print $url->host };
if ($@) { warn "\$url wasn't what I thought it was" }
but in most cases you would want to drill down into the error and find the mismatch between your expectations and the program's behavior.
Upvotes: 3