my $ua = LWP::UserAgent->new (max_size => 512); # note extra param my $tmpfile; foreach my $rev ("-", ('A'..'Z')) { $tmpfile = "$file$rev.$ext"; my $response = $ua->get("$path/$tmpfile"); # simpler interface ## you need to save $tmpfile here! last if $response->is_success; # better than yours }