my $m = WWW::Mechanize->new;
Replace with WWW::Mechanize->new( qw/ autodie 1 /);
getstore($url,$filename) or die "Can't download '$url': $@\n";
Get rid of LWP::Simple , replace with $m->mirror( $url, $filename ); autodie takes care of the dying
if ( -e -d $name ) {
While you can (since 5.9.1) chain/stack file-test operators in a case like this (it's the quivalent of -d $name && -e _) , if its a directory, it already exists (otherwise how can it be a directory ), so if you're going to test to see if its a directory, just use -d
Checking if a directory exists before creating the directory is a classic race condition --- some other program could make the directory after your program checks that it doesn't exist, but before it creates it -- this may or may not matter to your program
Since creating a directory is an atomic operation (either succeed or fail), simply try to create the directory -- if it already exists, creation will fail
Here is how I might write that
sub Dirpp { use Errno qw/ EACCES /; # permission denied my $newdir = "site00"; my $made = 0; while ( not $made = mkdir $name, 0755 ) { die $! if $! == EACCES; $newdir++; } return $name if $made; # if we made it, return new name return; }
This takes advantage of the magical string increment or auto-increment. auto-increment does overflow, so if that isn't desired, then I would write
sub DirPP { use Errno qw/ EACCES /; # permission denied my $word = "site"; my $counter = 1; my $name ; my $made = 0; while(1){ $name = sprintf '%s%3d', $word, $counter; last if not $made = mkdir $name, 0755 ; die $! if $! == EACCES; } return $name if $made; return; }
Why while(1) ? Because to me two sprintf looks clumsy
sub DirPo { use Errno qw/ EACCES /; # permission denied my $word = "site"; my $counter = 1; my $made = 0; my $name = sprintf '%s%3d', $word, $counter; ## ONE, PEE while ( not $made = mkdir $name, 0755 ) { die $! if $! == EACCES; $name = sprintf '%s%3d', $word, $counter; ## TWO, EEW } return $name if $made; return; }
Also, storing one file per directory is bizzare :)
In reply to Re: getting a while loop to terminate
by Anonymous Monk
in thread getting a while loop to terminate
by Aldebaran
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |