使用用户输入名称重命名文件

时间:2013-09-03 09:46:09

标签: perl perl-module

我想将临时文件“file3.c”重命名为用户输入文件名。 使用File :: copy中的重命名或移动命令不会重命名它。

use strict;
use warnings;
use File::Copy;

#input header file
print "Input file1:\n";
$input = <>;
open(FILE1, $input) || die "couldn't open the file!";

open(FILE3, '>>file3.c') || die "couldn't open the file!";
...
#some work on file3.c
...

close(FILE1); 
close(FILE3);

#renaming prepended temporary file name to original file name
rename("file3.c", "$input");

OUTPUT 没有重命名

如何重命名?

1 个答案:

答案 0 :(得分:5)

您可能只需要chomp您的输入即可删除换行符:

chomp(my $input = <>);

执行文件操作时,您应始终检查错误$!

rename($foo, $bar) or die "Cannot rename: $!";

此外,您通常应使用or代替||,因为||具有更高的优先级。例如,这是一个常见的初学者错误,很难发现:

open my $fh, "<", $file || die $!;  # WRONG!

由于逻辑或||的优先级高于逗号,,因此die语句永远不会发生,除非$file恰好是假值。

相关问题