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

I have a small script which runs on a number of different servers. Some of these servers do not have LWP module installed (and I cannot install it on them). I have the following eval test to determine if LWP is available...
if (eval "require LWP::UserAgent; 1") { my %post = ('key' => 'value'); my $ua = LWP::UserAgent->new(); my $content = $ua->post("http://www.mydomain/post.cgi",[%post])->a +s_string; #do something with the content ... } else { print "LWP not available"; }
This works quite nicely on most servers... Most servers have LWP and the POST works fine. Some don't and they get the else message above. However, a few servers report the following error:
Can't locate object method "post" via package "LWP::UserAgent" (perhap +s you forgot to load "LWP::UserAgent"?) at (eval 2) line 1.
How can I avoid this? Is the eval not a suitable way to test of LWP is available? Is there a better way to do this? Thanks so much...

Replies are listed 'Best First'.
Re: Testing if machine has LWP... not working
by ikegami (Patriarch) on Nov 22, 2006 at 02:06 UTC

    IIRC, post didn't exist in older versions of LWP::UserAgent. It's definitely consistent with the results you are getting. Instead, create a request using HTTP::Request::Common and pass it to $ua->request.

Re: Testing if machine has LWP... not working
by GrandFather (Saint) on Nov 22, 2006 at 01:43 UTC

    The documentation for post in LWP::UserAgent mentions using HTTP::Request::Common to do the work. Is it possible that that module is not available on some of your servers?


    DWIM is Perl's answer to Gödel
Re: Testing if machine has LWP... not working
by Cabrion (Friar) on Nov 22, 2006 at 01:44 UTC
    You should be checking $@ for an error after an eval.

      No need. eval returns undef on expection. Otherwise, it returns true because of the 1;. It would return true even without the 1; because require always returns true or an exception.

      Incidentally, eval EXPR is not needed here. eval BLOCK suffices.

      if (eval { require LWP::UserAgent })
Re: Testing if machine has LWP... not working
by Anonymous Monk on Nov 22, 2006 at 15:31 UTC
    Don't use string-eval, use block eval instead: eval { require LWP::UserAgent}