sub rename_filename{
my $file_name = shift;
my $count = shift;
my $upload_dir = shift;
my $path_to_file = $upload_dir . $file_name;
if(-e $path_to_file && -f $path_to_file){
if($file_name =~ /(.*)_(\d*)\.(.*)/){
# Already renamed so count on
$count = $2 + 1;
$file_name =~ s/(.*)_(\d*)\.(.*)/$1_$count\.$3/;
}
else{
# Not renamed so start counting
$file_name =~ s/(.*)\.(.*)/$1_$count\.$2/;
}
&rename_filename($file_name, $count, $upload_dir);
}
else{ return $file_name; }
}
Many thanks in advance!
sub rename_filename{
# Shift filename from (default) array '@argv' to locally-scoped variable $file_name
my $file_name = shift;
# Shift count from array '@argv' to local variable $count
my $count = shift;
# Shift upload directory path from array '@argv' to local variable $upload_dir
my $upload_dir = shift;
# Build full path to file
my $path_to_file = $upload_dir . $file_name;# If a file exists at that path and is an ordinary file
if(-e $path_to_file && -f $path_to_file){
# then if filename is in the form "<anything-or-nothing>_<any-number-(including zero)-of-digits>.<anything-or-nothing>"
if($file_name =~ /(.*)_(\d*)\.(.*)/){
# Filename was already used in renaming so increment the count
$count = $2 + 1;
# Replace previously-used filaname with initial name part, underscore, incremented count, dot, and filetype.
$file_name =~ s/(.*)_(\d*)\.(.*)/$1_$count\.$3/;
}
else{
# else filename not already used, so just stick an underscore and the count in the middle
$file_name =~ s/(.*)\.(.*)/$1_$count\.$2/;
}
# Rename the file
&rename_filename($file_name, $count, $upload_dir);
}
# else file does not exist or is not an ordinary file
else{ return $file_name; }
}
Jim