因此,我正在读取一个日历文件,以便在该文件中插入日期,并且我希望日期保持按时间顺序排列。当我找到日期应该放的位置时,问题就来了,文件已经超出了我想要插入的点。
我正在查看的日历文件如下所示:
# November 2010
11/26/2010
11/27/2010
11/28/2010
11/29/2010
11/30/2010
# December
12/24/2010
12/25/2010
12/26/2010
12/27/2010
12/28/2010
12/29/2010
12/30/2010我的代码看起来像这样:
while (my $line = <FILE>) {
if (substr($line, 0, 1) =~ m/\#/ || $line =~ m/calendar/) { #if the line is commented out or contains the calendar's name skip to next line
next;
}
chomp($line);
my ($temp_month, $temp_day, $temp_year) = split(/\//, $line, 3);
if ($year == $temp_year && $month == $temp_month && $day < $temp_day) {
?
}
}那么,对于如何指向文件中的前一个点,有什么建议吗?
发布于 2011-08-02 20:19:30
您需要在文件中随机移动的函数是seek。但是在Perl常见问题解答- How do I change, delete, or insert a line in a file, or append to the beginning of a file?中有更多关于如何处理这个问题的信息。
发布于 2011-08-02 20:37:15
这听起来像是Tie::File模块的一个很好的用途。您可以将文件视为数组,而不必担心文件指针的当前位置。它也不依赖于将整个文件加载到内存中-因此它可以处理大量文件。
use Tie::File;
tie @array, 'Tie::File', $file;
for (my $i =0; $i <= @array; $i++) {
if (/date comparison/*see note below) {
splice @array, $i, 0, $new_date;
}
}这将允许您使用perl的数组函数,如splice,来插入新行。
但是,你的日期比较策略也有一个很大的问题。如果文件中还没有给定的月、年组合的日期,该怎么办?您将循环遍历,并且找不到放置它的位置。查看timelocal,您可以使用它将两个日期转换为纪元时间,然后进行比较。
use Time::Local;
my $temp_epoch = timelocal(0,0,0,$temp_day,$temp_month -1, $temp_year-1900);
if ($epoch < $temp_epoch ) {
...
}发布于 2011-08-02 20:20:15
seek和tell将解决倒带问题。您最终将覆盖当前已有的行。懒惰的解决方案是使用Tie::File,另一种可能是在写出新版本时读取文件,然后在写完后用新版本替换旧版本。
https://stackoverflow.com/questions/6911197
复制相似问题