----- Original Message ----- From: "John W. Krahn" <[EMAIL PROTECTED]>
To: "Perl Beginners" <beginners@perl.org>
Sent: Wednesday, May 11, 2005 5:02 PM
Subject: Re: rename files
[EMAIL PROTECTED] wrote:Hi,
Hello,
I want to rename all the files in a directory with filenames starting 1.jpg to n.jpg.
Why this code does not rename the files?
opendir(DIR, "/tmp") or die "can not open dir: $!\n"; my @files = grep {/.jpg/ } readdir(DIR); closedir(DIR);
my $count = 1;
foreach (@files){ print "@files\n"; # works: prints all the files my $new = $_; $new =~ s/(.*)(.jpg)/$count$2/;
rename($_, $new) or die "can not rename file: $!\n"; print "$_ renamed to $new\n"; $count++; }
You want something like this:
my $dir = '/tmp';
opendir DIR, $dir or die "Cannot open $dir: $!"; my @files = map "$dir/$_", grep /\.jpg$/, readdir DIR; closedir DIR;
my $count = 1;
for my $file ( @files ) { print "$file\n"; my $new = "$dir/" . $count++ . '.jpg'; if ( -e $new ) { print "$new already exists.\n"; next; } rename $file, $new or warn "Cannot rename $file to $new: $!"; print "$file renamed to $new\n"; }
__END__
Jay, sort implemented. Thank you. Very nice, John, (as expected from you.) Thanks.
John -- use Perl; program fulfillment
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>