in reply to Renaming files in directory

Hi WisDomSeeKer34,

If you just want to rename files, then I would suggest that you just use the rename built-in function of Perl, rather than using the File::Copy module.

Also, I would suggest that the glob function is, in at least 95% of the cases, much easier to use than the opendir/readdir combination for at least three reasons: it is simpler (one code line instead of two), it returns the filenames with their path (so you don't have to add the path yourself), and it removes special "files" such as . and .. from the file list.

Then, unless you can really be sure that your file list will always have less than 16 files, don't hard code your list as you did. Increment you file names as you go, or build a much larger list, for example:

my @names = ('a'..'zz');
so that you can be sure you'll not run out of names.

Finally, using a "c-style" loop is probably not a good idea (and it is really not perlish). You could try something like this (assuming you made the other changes I mentioned, especially glob):

my $name = 'a'; for my $file_in (@files) { rename $file_in, $name; $name++; }
Then, there is a slight problem: you don't say clearly where you want the output files to be created. Probably you want to first cd to the directory, or else want to change the loop above to:
for my $file_in (@files) { rename $file_in, "$directory/$name"; $name++; }
HTH.

Replies are listed 'Best First'.
Re^2: Renaming files in directory
by Anonymous Monk on Jan 05, 2018 at 23:42 UTC
    If you just want to rename files, then I would suggest that you just use the rename built-in function of Perl, rather than using the File::Copy module.

    why? "If possible, move() will simply rename the file."

      Sure, the move function the File::Copy module will rename the file, it is just a bit simpler to use a builtin function (such as rename) when it exists.
        Thank you for your anwers. I have so much on my mind right now, that I have to get back to it somewhat later.
        But thank you for your answers. I appreciate it.
        I have looked at your posts and I have tried the code of haukex and it works, but I don't really understand the code. Can you look again at the code that I have written?
        #!bin/perl use strict; use warnings; use File::Spec; my $directory = '/home/porter/Videos/blue/'; opendir(DIR,$directory); my @oldfiles = File::Spec->no_upwards( readdir DIR ); closedir(DIR); my @newfiles = qw(Alfa Bèta Gamma Delta Epsilon Zèta Èta Thèta Iota K +appa Lambda Mu Nu Ksi Omikron); my $a = @oldfiles; my $b = @newfiles; if ( $a ne $b ) { print "the numbers are not equal\n" and die; } for (my $i = 0; $i < $a; $i++) { rename $oldfiles[$i],$newfiles[$i]; }
        The programs exits with code 0 so that is okay, but it doesn't do what it is supposed to do.