揮発性のメモ2

http://d.hatena.ne.jp/iww/

ファイル一覧

あるディレクトリの最初のファイル名だけ表示するスクリプト

 1:#!/usr/bin/perl
 2:use strict; use warnings;
 3:
 4:if( opendir(my $dh, "/tmp/hoge/") ){
 5:    print "dh=$dh\n";
 6:    if( my $f = readdir $dh ){
 7:        print "f=$f\n";
 8:    }
 9:    closedir $dh;
10:}
$ ./hoge.pl
Value of readdir() operator can be "0"; test with defined() at ./hoge.pl line 6.
dh=GLOB(0x15990)
f=unko.txt

なぜかWarningが出る。


あるディレクトリのファイル名一覧を表示するスクリプト

 1:#!/usr/bin/perl
 2:use strict; use warnings;
 3:
 4:if( opendir(my $dh, "/tmp/hoge/") ){
 5:    print "dh=$dh\n";
 6:    while( my $f = readdir $dh ){
 7:        print "f=$f\n";
 8:    }
 9:    closedir $dh;
10:}
$ ./hoge.pl
dh=GLOB(0x15990)
f=unko.txt
f=..
f=.

whileの中だとなぜかWarningが出ない。

# 指定ディレクトリにあるファイル名をフルパスで最初の1個だけ返す関数
sub readdirfirstfile {
    my $dir = $_[0];
    
    if( opendir(my $dh, $dir) ){
        my @flist;
        while( my $f = readdir($dh) ){
            if( -f "$dir/$f" ){
                push(@flist,"$dir/$f");
            }
        }
        @flist = sort @flist;
        return $flist[0];
    }
    return;
}