dgoins has asked for the wisdom of the Perl Monks concerning the following question:

After doing a opendir and readdir, how do I determine if this item(file or directory) is the the last item in the current directory?

Replies are listed 'Best First'.
Re: Determine if item is last one
by AltBlue (Chaplain) on Nov 15, 2002 at 19:59 UTC

    when used in scalar context, readdir returns undef when there are no more entries:

    opendir DIR, q{.} or die $!,$/; my $last; while (my $file = readdir DIR) { $last = $file; } print $last; ## this prints the last file closedir DIR;
    yet, keep in mind that there is no order garanteed, so don't count on that.

    OTOH, if you use readdir in list context, it will return you a null list when no entries are available.

    opendir DIR, q{.} or die $!,$/; my @files = readdir DIR; closedir DIR; print $files[-1]; ## this prints the last file
    Here you have control on the file ordering in the usual list sorting manner:
    ## sorted by name, case sensitive my @files = sort {$a cmp $b} readdir DIR;

    --
    AltBlue.
Re: Determine if item is last one
by hawtin (Prior) on Nov 15, 2002 at 20:01 UTC

    Given the fact that a directory handle is a typeglob (approximately) and recursion is always with us, I find the best way to do readdirs is "all at once", this reduces the chance that I will have two directory handles with the same name interfere with each other.

    { my(@files,$file); local(*DIR); opendir(DIR,$dir_name); @files = readdir(DIR); closedir(DIR); foreach $file (@files) { next if(/^\.\.?/); ... } }

    If you adopt this strategy then your question becomes "how do I find out if this item is last one on the list", and therefore very easy to answer.

Re: Determine if item is last one
by Wonko the sane (Curate) on Nov 15, 2002 at 20:01 UTC
    You could do that with something like this.
    #!/usr/local/bin/perl -w use strict; opendir( DIR, './' ); my @files = readdir( DIR ); closedir( DIR ); my $i = scalar @files; foreach my $file ( @files ) { $i--; # do something with the items in list if ( $i == 0 ) { # do something special with last one. } }

    Wonko

      Well, after

      opendir( DIR, './' ); my @files = readdir( DIR ); closedir( DIR );
      you can get the last element with my $last = $files[-1];Hardly a good golfer, just an avid reader of perldata ;-)