Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: rename files with mtime

by Narveson (Chaplain)
on Feb 15, 2009 at 03:56 UTC ( [id://743908]=note: print w/replies, xml ) Need Help??


in reply to rename files with mtime

You do realize, I trust, that your program does not rename any files?

$file =~ s/\d+/$datestamp/ changes the contents of your variable $file. To use your own example, if $file contains maillog.1.gz and the datestamp is 20090213, then after the substitution $file will contain maillog.20090213.gz. The file on disk, however, is still named maillog.1.gz.

You are wise to be printing the outcome of the substitution so that you can review it. Assuming you are satisfied with your printout, how are you going to rename the file? In order to follow the template for rename, which is

rename OLDNAME,NEWNAME

you'll need to declare a second variable. The idiomatic way is

(my $new_name = $file) =~ s/\d+/$datestamp/;

after which you can say

rename $file, $new_name;

Replies are listed 'Best First'.
Re^2: rename files with mtime
by grinder (Bishop) on Feb 15, 2009 at 10:00 UTC

    Speaking of idioms...

    after which you can say
    rename $file, $new_name;

    The following idiom helps prevents renaming disasters:

    rename $file, $new_name unless -e $new_name;

    That is, don't rename a file if it would cause an existing file to be unlinked. It's easier to fix up the mess of a file that hasn't been renamed than one that no longer exists...

    • another intruder with the mooring in the heart of the Perl

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://743908]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-04-19 09:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found