perlnoob
perlnoob

Reputation: 107

Rename a file with perl

I have a file in a different 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.

Upvotes: 1

Views: 2564

Answers (4)

justintime
justintime

Reputation: 3631

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.

Upvotes: 0

MJB
MJB

Reputation: 7686

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

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

should be

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

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

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...)

Upvotes: 1

Sinan &#220;n&#252;r
Sinan &#220;n&#252;r

Reputation: 118128

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 = "${_}[email protected]";

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.

Upvotes: 2

Related Questions