Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!
I'm trying to rename some files in this directory, can't figure it out why it is not renaming the files, here is the code I am using;
... my $dir_path = "/my_dir"; my @dir = <$dir_path/*.*>; if (@dir) { foreach (@dir) { next if -d; my $temp_f_name = basename( $_ ); # get just the file extension (my $file_extention = $temp_f_name)=~s/^([^_]+_)(.*)(\.\w{3,4})\z$ +/$3/eg; my $renamed_file ="oldsince_"."$file_extention"; rename($temp_f_name, $renamed_file ) unless $temp_f_name eq $r +enamed_file or warn "Couldn't rename: $!\n"; } } ...

Thanks!

Replies are listed 'Best First'.
Re: Trying to rename files in directory
by Eliya (Vicar) on Feb 15, 2012 at 03:42 UTC

    Have you printed out the source and target file names to see if they really are what they should be?

    One problem could be that basename strips the directory component, so the source file ($temp_f_name) wouldn't be found in case the script is called from outside of the directory /my_dir.

    Also, rename(...) unless ... or warn ... probably doesn't do what you expect.  I suppose you meant

    unless ($temp_f_name eq $renamed_file) { rename($temp_f_name, $renamed_file ) or warn "Couldn't rename: +$!\n"; }
Re: Trying to rename files in directory
by tangent (Parson) on Feb 15, 2012 at 03:50 UTC
    I could be wrong but try it without the "eg" in the substitution:
    s/^([^_]+_)(.*)(\.\w{3,4})\z$/$3/;
    And then change your warning to:
    warn "Couldn't rename $temp_f_name to $renamed_file, $!\n";
    to see what else is happening. If that's no good put in
    print "About to rename $temp_f_name to $renamed_file\n";
    before the rename()