Puzzled Guy
January 18th, 2010, 03:24 AM
Hi
I have a program for renaming files. I give it all the proper input but it doesn't seem to work.
This is the program:
#!/usr/bin/perl
use strict;
use warnings;
my($dir, $oldpat, $newpat);
print "Directory: ";
chomp($dir=<STDIN>);
print "Old pattern: ";
chomp($oldpat=<STDIN>);
print "New pattern: ";
chomp($newpat=<STDIN>);
opendir(DH, $dir) || die "Cannot open $dir: $!";
my @files=readdir DH;
close(DH);
my $oldname;
foreach(@files) {
$oldname=$_;
s/$oldpat/$newpat/;
next if (-e "$dir/$_");
if (! rename "$dir/$oldpat", "$dir/$_") {
warn "Could not rename $oldname to $_: $!";
} else {
print "File $oldname renamed to $_\n";
}
}
Here is the input and the resulting output:
hope@Hope-Laptop:~/Desktop/Perl$ perl renamer.pl
Directory: /home/hope/Desktop/Perl
Old pattern: uni
New pattern: bi
Could not rename uniword.pl to biword.pl: No such file or directory at renamer.pl line 24, <STDIN> line 3.
hope@Hope-Laptop:~/Desktop/Perl$
I have a program for renaming files. I give it all the proper input but it doesn't seem to work.
This is the program:
#!/usr/bin/perl
use strict;
use warnings;
my($dir, $oldpat, $newpat);
print "Directory: ";
chomp($dir=<STDIN>);
print "Old pattern: ";
chomp($oldpat=<STDIN>);
print "New pattern: ";
chomp($newpat=<STDIN>);
opendir(DH, $dir) || die "Cannot open $dir: $!";
my @files=readdir DH;
close(DH);
my $oldname;
foreach(@files) {
$oldname=$_;
s/$oldpat/$newpat/;
next if (-e "$dir/$_");
if (! rename "$dir/$oldpat", "$dir/$_") {
warn "Could not rename $oldname to $_: $!";
} else {
print "File $oldname renamed to $_\n";
}
}
Here is the input and the resulting output:
hope@Hope-Laptop:~/Desktop/Perl$ perl renamer.pl
Directory: /home/hope/Desktop/Perl
Old pattern: uni
New pattern: bi
Could not rename uniword.pl to biword.pl: No such file or directory at renamer.pl line 24, <STDIN> line 3.
hope@Hope-Laptop:~/Desktop/Perl$