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

Hi everyone. I need some help regarding the code below. I would like to save the latency results into a file whenever a measurement is carried out. Furthermore I would to add a progress bar when the measurements being done. Thank your for your continued support.

#!/usr//bin/perl -w use LWP::UserAgent; use Time::HiRes 'time','sleep'; $ua = LWP::UserAgent->new; $request = new HTTP::Request('GET', "http://http://www.computerhope.co +m/file.com"); $start = time( ); $response = $ua->request($request); $end = time( ); $latency = $end - $start; print length($response->as_string( )), " bytes received in $latency s +econds\n";

Replies are listed 'Best First'.
Re: SAVE DATA
by Corion (Patriarch) on May 07, 2012 at 07:37 UTC

    Have you looked at LWP::UserAgent::get? It can save the response directly to a file and it also offers you the option of a progress callback.

Re: SAVE DATA
by zentara (Cardinal) on May 07, 2012 at 11:07 UTC
    Here is how to monitor progress with LWP
    #!/usr/bin/perl use strict; use warnings; use LWP::Simple; use LWP::UserAgent; my $urlin = shift || "http://zentara.net/zentara.avi"; my $infile = "zentara1.avi" ; print "gettin video file : $infile\n"; # don't buffer the prints to make the status update $| = 1; open(IN,"> $infile") or die "$_\n"; my $ua = LWP::UserAgent->new(); my $received_size = 0; my $request_time = time; my $last_update = 0; my $response = $ua->get($urlin, ':content_cb' => \&callback, ':read_size_hint' => 8192, ); print "\n"; close IN; #play the avi file with mplayer # system( "mplayer $infile" ); ############################################# sub callback { my ($data, $response, $protocol) = @_; my $total_size = $response->header('Content-Length') || 0; $received_size += length $data; # write the $data to a filehandle or whatever should happen # with it here. print IN $data; my $time_now = time; # this to make the status only update once per second. return unless $time_now > $last_update or $received_size == $total_s +ize; $last_update = $time_now; print "\rReceived $received_size bytes"; printf " (%i%%)", (100/$total_size)*$received_size if $total_size; printf " %6.1f/bps", $received_size/(($time_now-$request_time)||1) if $received_size; } __END__

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh