Perl—;创建文件的编号备份副本

Perl—;创建文件的编号备份副本,perl,file-exists,file-copying,Perl,File Exists,File Copying,我正在将数据提取到某个文本文件中,但首先我希望脚本检查文件是否存在,然后在某个文件夹中创建副本。如果它仍然存在于同一文件夹中,请保存它,但像值_1或_2一样追加。。。取决于最后一个文件的值 这是我目前的剧本 if (-e "/tmp/POP_Airtime_Week1.txt"){ copy("/tmp/POP_Airtime_Week1.txt","/tmp/POP") || die "cannot copy file"; # If the file exists creat

我正在将数据提取到某个文本文件中,但首先我希望脚本检查文件是否存在,然后在某个文件夹中创建副本。如果它仍然存在于同一文件夹中,请保存它,但像值_1或_2一样追加。。。取决于最后一个文件的值

这是我目前的剧本

if (-e "/tmp/POP_Airtime_Week1.txt"){

    copy("/tmp/POP_Airtime_Week1.txt","/tmp/POP") || die "cannot copy file";
    # If the file exists create a copy in /tmp/POP

    #################################
    # IF FILE EXISTS IN /tmp/POP copy the file but rename it to 
    # POP_Airtime_Week1_1.txt then increase the numbers each time
    # the script is run and a new copy needs to be created.
    ##################################

    unlink ("/tmp/POP_Airtime_Week1.txt");

}
如果存在
/tmp/POP/POP\u Airtime\u Week1.txt
,则复制它,但将其另存为
/tmp/POP/POP\u Airtime\u Week1.txt
。下次我运行脚本并且
/tmp/POP/POP\u Airtime\u Week1.txt
存在时,复制它并将其保存为
/tmp/POP/POP\u Airtime\u Week1\u 2.txt


如何执行此操作?

当目标文件存在时,您可以增加一个变量:

my $name = "POP_Airtime_Week1";
if (-e "/tmp/POP/$name.txt") {
    my $num = 1;
    $num ++ while (-e "/tmp/POP/$name\_$num.txt");
    copy("/tmp/$name.txt","/tmp/POP/$name\_$num.txt") or die "cannot copy file";
} else {
    copy("/tmp/$name.txt","/tmp/POP/$name.txt") or die "cannot copy file";
}

不过要注意。如果您(或您和其他人)运行多个脚本实例,则可能存在争用情况。

缺少的只是一个循环和一个计数器。为什么不使用logrotate之类的现有工具?是否应该有“use File::Copy;”在代码的开头?@JonathanLeffler:我只是认为这是一个未完成的文件名:)已修复。我尝试在第一次运行它时,它会创建并复制一个新文件/tmp/POP/POP_Airtime_Week1_1;下次运行时,不会创建/tmp/POP/POP_Airtime_Week1_2,之前的数据也不会写入任何其他文件。但是/tmp/POP\u Airtime\u Week1已被覆盖。@OmbongiMoraa:脚本从未覆盖原始文件。它只在POP子目录中创建副本。对不起,忘了说我包含了取消链接(“/tmp/POP_Airtime_Week1.txt”);如我的问题所述。这允许删除文件的/tmp副本,因为我想让/tmp/POP处理旧副本。如果我不取消/tmp文件的链接,那么我会得到它存在的错误,并且我的脚本会提前终止。@OmbongiMoraa:适合我。如果文件存在,会出现什么错误?您是否创建了
/tmp/POP
目录?
 my $i = 0;
 my $fname = $file;
 for (;;) {
     last unless -f $fname;
     $i++;
     $fname = "${file}_$i";
 }
 # $fname is new unused file name, copy to it