开发者

Rename a file with perl

I have a file in a dif开发者_开发问答ferent folder I want to rename in perl, I was looking at a solution earlier that showed something like this:

#rename
for (<C:\\backup\\backup.rar>) {
    my $file = $_;
    my $new = $file . 'backup' . $ts . '.rar';  
    rename $file, $new or die "Error, can not rename $file as $new: $!";
}

however backup.rar is in a different folder, I did try putting "C:\backup\backup.rar" in the <> above, however I got the same error.

C:\Program Files\WinRAR>perl backup.pl
String found where operator expected at backup.pl line 35, near "$_ 'backup'"
        (Missing operator before 'backup'?)
syntax error at backup.pl line 35, near "$_ 'backup'"
Execution of backup.pl aborted due to compilation errors.

I was using

# Get time
my @test = POSIX::strftime("%m-%d-%Y--%H-%M-%S\n", localtime);
print @test;

To get the current time, however I couldn't seem to get it to rename correctly.

What can I do to fix this? Please note I am doing this on a windows box.


Pay attention to the actual error message. Look at the line:

my $new = $_ 'backup'. @test .'.rar';

If you want to interpolate the contents of $_ and the array @test into a string like that, you need to use:

my $new = "${_}backup@test.rar";

but I have a hard time making sense of that.

Now, strftime returns a scalar. Why not use:

my $ts = POSIX::strftime("%m-%d-%Y--%H-%M-%S", localtime);
my $new = sprintf '%s%s%s.rar', $_, backup => $ts;

Incidentally, you might end up making your life much simpler if you put the time stamp first and formatted it as YYYYMMDD-HHMMSS so that there is no confusion about to which date 04-05-2010 refers.


The line

my $new = $_ 'backup'. @test .'.rar';

probably should read

my $new = $file . 'backup' . @test . '.rar';

(You were missing a concatenation operator, and it is clearer to use the named variable from the line before than reusing $_ there...)


I think you missed the string concat symbol . (the period) :

my $new = $_ 'backup'. @test .'.rar';

should be

my $new = $_ . 'backup' . @test . '.rar';


A slight side issue but you don't need

for (<C:\\backup\\backup.rar>) {
   my $file = $_;
   .....
}

The < > construct would be useful if you were expanding a wildcard but you are not. Be thoughtful of future readers of this code (you in a year!) and write

my $file = 'C:\backup\backup.rar' ;

Note the single quotes which doen't expand backslashes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜