You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Perl脚本中仅复制FTP服务器上的当日最新文件?

解决Perl FTP脚本仅复制当日文件的问题

首先明确你拿到的1697627482是什么:这是Unix时间戳,代表从1970年1月1日00:00:00 UTC到文件修改时刻的总秒数。你可以用Perl自带模块转成可读时间,示例代码:

use Time::Piece;
my $mdtime = $ftp->mdtm($fl);
my $dt = localtime($mdtime);
print "文件修改时间:", $dt->strftime("%Y-%m-%d %H:%M:%S"), "\n";

下面是修改后的完整核心逻辑,实现仅复制当日文件:

修改后的核心代码

use strict;
use warnings;
use Net::FTP;
use Time::Piece;

# 保留你的FTP初始化代码
my $ftp = Net::FTP->new( $host, Timeout => 360, Passive => 1, Debug=>1 ) 
    or die "Error connecting to $host: $!\n";
$ftp->binary();
$ftp->login($User,$Pass) or die "Cannot login to $User\n";
$ftp->cwd($remote_dir) or die "Could not change remote working directory to $remote_dir\n";

# 计算当日时间范围的Unix时间戳
my $today = localtime;
# 当日0点的时间戳
my $start_of_day = $today->strptime($today->strftime("%Y-%m-%d"), "%Y-%m-%d")->epoch;
# 次日0点的时间戳(作为当日结束边界)
my $end_of_day = $start_of_day + 86400;

# 筛选符合条件的文件:匹配文件名格式+修改时间在当日
my @file2copy;
foreach my $fl ($ftp->ls()) {
    # 匹配FPZB01_xxxxxx.txt格式的文件
    next unless $fl =~ /^FPZB01_\d+\.txt$/;
    my $mdtime = $ftp->mdtm($fl);
    # 跳过无法获取修改时间的文件
    next unless defined $mdtime;
    # 判断是否在当日时间区间内
    if ($mdtime >= $start_of_day && $mdtime < $end_of_day) {
        push @file2copy, $fl;
    }
}

# 复制筛选后的文件
foreach my $file (@file2copy) {
    print "Getting $file\n" if $debug;
    eval {
        $ftp->get($file, "$local_dir/$file") 
            or die "Can't get file $file\n";
    };
    if ($@) {
        if ($@ =~ /Timeout/) {
            print "Got a timeout Issue: $@";
        } else {
            print "Error getting $file: $@";
        }
    }     
}

print "copying ends\n";
exit 0;

关键说明

  • 用Time::Piece处理时间,避免手动计算时间戳的误差
  • 先通过正则匹配文件名格式,再判断修改时间,双重过滤更精准
  • 增加defined $mdtime判断,规避部分FTP服务器不支持mdtm命令的情况
  • 优化了错误处理逻辑,区分超时和其他文件获取失败场景

内容的提问来源于stack exchange,提问作者Zilore Mumba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 01:13:12