在perl中对目录进行排序,并考虑数字 [英] Sorting a directory in perl, taking numbers into account

查看:151
本文介绍了在perl中对目录进行排序,并考虑数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我需要某种 Schwartzian变换这项工作有效,但是我很难弄清楚,因为perl不是我最强的语言.

I think I need some sort of Schwartzian Transform to get this working, but I'm having trouble figuring it out, as perl isn't my strongest language.

我有一个目录,其内容如下:

I have a directory with contents as such:

album1.htm
album2.htm
album3.htm
....
album99.htm
album100.htm

我正在尝试从该目录(在本例中为album100.htm)中获取编号最高的专辑.请注意,文件上的时间戳并不是确定事物的可靠方法,因为人们在事后添加了旧的缺失"专辑.

I'm trying to get the album with the highest number from this directory (in this case, album100.htm). Note that timestamps on the files are not a reliable means of determining things, as people are adding old "missing" albums after the fact.

以前的开发人员只使用了下面的代码段,但是一旦目录中有9张以上的相册,这显然会崩溃.

The previous developer simply used the code snippet below, but this clearly breaks down once there are more than 9 albums in a directory.

opendir(DIR, PATH) || print $!;
@files = readdir(DIR);
foreach $file ( sort(@files) ) {
    if ( $file =~ /album/ ) {
        $last_file = $file;
    }
}

推荐答案

如果您只需要查找编号最高的专辑,则无需真正排序列表,只需遍历列表并跟踪最大.

If you just need to find the album with the highest number, you don't really need to sort the list, just run through it and keep track of the maximum.

#!/usr/bin/perl 

use strict;
use warnings;

my $max = 0;

while ( <DATA> ) {
    my ($album) = $_ =~ m/album(\d+)/;
    $max = $album if $album > $max;
}

print "album$max.htm";

__DATA__
album1.htm
album100.htm
album2.htm
album3.htm
album99.htm

这篇关于在perl中对目录进行排序,并考虑数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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