读取Perl中最后修改的文件 [英] read the last modified file in perl

查看:184
本文介绍了读取Perl中最后修改的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取Perl目录中最后修改的文件的内容

How can I read the content of the last modified file in a directory in perl

我有一个收到短信的工具,我想发出最后一个修改后的文件存储在gammu / inbox目录中,其中包含perl脚本

I have a tool for received sms and I want to give out the content of the last modified file , which is stored in gammu/inbox directory , with a perl script

,例如:该脚本检查了文件夹中的新的短信(gammu / inbox)他们是从最后一个短信中发出的内容。

for example: the script checked if a new sms in folder(gammu/inbox), are they, then give out the content from the last sms.

推荐答案

根据每个文件的年龄对目录进行排序,使用 -M 文件测试运算符。最近修改的文件将是列表中的第一个。

Sort the directory according to the age of each file, using the -M file test operator. The most recently modified file will then be the first in the list

此程序显示原理。它找到当前工作目录中的最新文件,打印其名称并打开它进行输入

This program shows the principle. It finds the latest file in the current working directory, prints its name and opens it for input

如果要为目录执行此操作,那么cwd就是可能最简单的只是到 chdir ,并使用这个代码,而不是尝试 opendir 一个特定的目录,那么你会必须在每个文件之前建立完整的路径,然后才能使用 -M

If you want to do this for a directory other that the cwd then it is probably easiest just to chdir to it and use this code than to try to opendir a specific directory, as then you will have to build the full path to each file before you can use -M

use strict;
use warnings 'all';
use feature 'say';

my $newest_file = do {
    opendir my $dh, '.' or die $!;
    my @by_age  = sort { -M $a <=> -M $b } grep -f, readdir $dh;
    $by_age[0];
};

say $newest_file;

open my $fh, '<', $newest_file or die qq{Unable to open "$newest_file" for input: $!};

如果您正在使用一个相当大的目录,那么这可能需要一些时间作为 stat 操作相当慢。您可以使用 Schwartzian变形改善这一点,以便 stat 每个文件只调用一次

If you are working with a sizeable directory then this may take some time as a stat operation is quite slow. You can improve this a lot by using a Schwartzian Transform so that stat is called only once for each file

my $newest_file = do {

    opendir my $dh, '.' or die $!;

    my @by_age  = map $_->[0],
    sort { $a->[1] <=> $b->[1] }
    map [ $_, -M ], readdir $dh;

    $by_age[0];
};

如果你想要一些真正的 ,那么只需单击一次文件,跟踪到目前为止最新发现。像这样

If you want something really fast, then just do a single pass of the files, keeping track of the newest found so far. Like this

my $newest_file = do {

    opendir my $dh, '.' or die $!;

    my ($best_file, $best_age);

    while ( readdir $dh ) {

        next unless -f;
        my $age = -M _;

        unless ( defined $best_age and $best_age < $age ) {
            $best_age = $age;
            $best_file = $_;
        }
    }

    $best_file;
};

这篇关于读取Perl中最后修改的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆