Perl – Web hit function using LWP::UserAgent

Published on Author gryzli

Often I need to issue web hit from a perl code, and re-inventing the wheel with LWP::UserAgent or WWW::Curl::Easy sometimes is too overdose for me.  That’s why I decided to write some semi-universal function called “web_hit()” which could be easily used for issuing web hits.


Important notices:

  • The function always generates POST requests
  • The arguments which are accepted are as follows:
    • URL – this must be the first argument
    • POST_DATA – this must be the second argument, and could be reference to a HASH. The keys of the hash will be used as variable names, and the values as values.
    • \$result – Reference to a result variable, where you will get back the results


Here is the definition itself:

web_hit() definition

# --- 
# web_hit() - Function for issuing POST hit to URL with given parameters
sub web_hit {
# ---
        use LWP::UserAgent;
        my $url         = shift;
        my $post_data   = shift;
        my $result      = shift;

        my $ua = new LWP::UserAgent;
        my $response    = $ua->post($url,$post_data);
        my $content     = $response->content;
        my $return_code = $response->code;

        # If we have $result provided, update it 
        $$result{content}               = $content if defined $result;
        $$result{return_code}           = $return_code if defined $result;

        return 1;
# END web_hit()


The usage is pretty straight-forward, here are some examples:

my %temp_result;
my $URL="";
use Data::Dumper;

if (! web_hit($URL,{},\%temp_result) ){
   print "Error issuing web hit to $URL\n";
   print Dumper (%temp_result);