Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Always Looping

by jesuashok (Curate)
on Mar 27, 2006 at 07:07 UTC ( #539380=perlquestion: print w/ replies, xml ) Need Help??
jesuashok has asked for the wisdom of the Perl Monks concerning the following question:

Hi All

I apreciate if anybody help me in this little problem... I just want to store an image from a url in a variable, but sometimes anything go wrong, and the routine can't open the url...so i create this code:

$size = 0; use LWP::Simple; while ($size == 0) { my $data2 = LWP::Simple::get $site; my $size = length($data2); print "$size\n"; }

My wish is that, when the image are really stored in variable $data, the loop stop, and the programe continue... but my problem is that the loop is continually looping..

Somebody can help me?

"Keep pouring your ideas"

Comment on Always Looping
Download Code
Re: Always Looping
by Corion (Pope) on Mar 27, 2006 at 07:12 UTC

    The problem is that you are not using strict, or rather, you are not Coping With Scoping. You actually have two variables $size - one, the global $size which you set to 0 at the top of your program, and another, $size, which you declare in the loop and set it to the length of your data. You should do away with the inner my and the script should work:

    use strict; use LWP::Simple; my $size; my $data2; while (! length $data2) { $data2 = LWP::Simple::get($site); if (! length $data2) { warn "Couldn't get a response from '$site', sleeping"; sleep 5; # give the website some time }: }; ...
      I'd always try to avoid a loop which could continue to fail like this. What if the file is deleted? You'll be looping forever.
      use strict; use LWP::Simple; my $data = ""; my $try_count = 0; while ($try_count++ < 5) { $data = LWP::Simple::get('http://somedomain/'); last if defined $data; print "were is this file?\n"; sleep(5); };
      I also changed the criteria for success to check for 'definedness', because the LWP::Simple::get() function will explictly return undef if it fails.
      ---
      my name's not Keith, and I'm not reasonable.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://539380]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2014-07-24 03:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (156 votes), past polls