Hello all,
I wrote a code that renames files, such that it changes the extension of any file to .xml extension. The program is recursive to traverse all files and subdirectories in a certain directory, and it takes a path of a directory as argument. However, the code I wrote does the renaming only for the first file in the folder and then displays an error message saying "No such file or directory" at the line performing renaming for any other file. I don't know why it is doing so. Can anyone please help me?
use Cwd; # module for finding the current working directory
$|=1; # turn off I/O buffering
# This subroutine takes the name of a directory and recursively scans
# down the filesystem from that point looking for files named "core"
sub ScanDirectory{
my ($workdir) = shift;
print "Work dir = $workdir\n";
my ($startdir) = &cwd; # keep track of where we began
chdir($workdir) or die "Unable to enter dir $workdir:$!\n";
opendir(DIR, ".") or die "Unable to open $workdir:$!\n";
my @names = readdir(DIR) or die "Unable to read $workdir:$!\n";
closedir(DIR);
foreach my $name (@names){
next if ($name eq ".");
next if ($name eq "..");
if (-d $name){ # is this a directory?
&ScanDirectory($name);
next;
}
else { # this is a file
print "Name = $name\n";
$newName = $name;
$newName =~ s/\..*//;
$newName .= ".xml";
$result = rename($name, $newName)
or die "cannot rename $name to $newName:$!";
}
chdir($startdir) or
die "Unable to change to dir $startdir:$!\n";
}
}
&ScanDirectory($ARGV[0]);
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.