CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
rename files in DIR using autoincrement for the file numbers

 



zolteck06
New User

Apr 9, 2013, 9:46 AM

Post #1 of 2 (327 views)
rename files in DIR using autoincrement for the file numbers Can't Post

I have a code built to rename files in a DIR
using the rename function, what I would like to do is append to the
end of the filename a number that auto inctements I included the code and
I would appreaiate any suggestion

#!/usr/bin/perl -w

$files ='/root/temp2/perl/test3';
$zolteck = function2()
opendir(DIR, $files) or die "Cannot open directory: $!";
@files = readdir(DIR);
closedir(DIR);

foreach (@files){
@files = sort(@files);
for($i = 0 ; $i <= 2 ; $i++){
shift @files;
}
$old = $_;
s/file*/zolteck/;
rename($old, $_) or print "Error renaming: $old\n";
}

#END
#the filenames are all named file1, file2 file3 etc..here you can see I renamed the 'file' portion of the file with zolteck, but I would like to append a number to the end of the file...I'm new and I hope this makes sense.


Kenosis
User

Apr 9, 2013, 10:09 AM

Post #2 of 2 (324 views)
Re: [zolteck06] rename files in DIR using autoincrement for the file numbers [In reply to] Can't Post

Always:


Code
use strict; 
use warnings;


at the top of your scripts.

Use lexically-scoped variables (my).

Consider using a glob (<>) instead of reading the directory contents.

It isn't necessary to sort the files--especially through each iteration of the file list. You can safely omit the following:


Code
@files = sort(@files); 
for($i = 0 ; $i <= 2 ; $i++){
shift @files;
}


Consider just concatenating the number to the file name before renaming.

Given the above, consider the following:


Code
use strict; 
use warnings;

my $files = '/root/temp2/perl/test3';

my $i = 1;
for (<$files*>) {
rename $_, $_ . $i++ or print "Error renaming: $_\n";
}


Hope this helps!


(This post was edited by Kenosis on Apr 9, 2013, 10:10 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives