in reply to Pulling a file with a given extension

That's what file globs are for.
my $datfile = (glob '*.dat')[0];

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^2: Pulling a file with a given extension
by Skeeve (Parson) on Oct 18, 2005 at 18:21 UTC
    Be aware though that a glob might be slower than a loop:
    #!/usr/bin/perl use strict; use warnings; use Benchmark qw( cmpthese ); sub globber { return(( glob '*.xml')[0]); } sub opener { opendir my $dir, '.'; my $file; while (defined($file= readdir $dir)) { last if $file=~ /\.xml$/; } closedir $dir; return $file; } cmpthese(5000, { globber => \&globber, opener => \&opener, });
              Rate globber  opener
    globber  654/s      --    -76%
    opener  2688/s    311%      --
    

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

      That all depends ... on whether you manage to get the opener to work ;-)

      I'd rather go with a slow function that was fast to write than a fast function that was slow and error prone to write. I can always speed up working code (or, failing that, fall back to the original slow code) much easier than taking fast code and making it work ;-)

      (Note - this is in no way intended to say that the above code doesn't work, only that I've seen many people get fooled when trying to use the *dir functions - including myself.)

Re^2: Pulling a file with a given extension
by rashley (Scribe) on Oct 18, 2005 at 18:21 UTC
    Oy! Do I feel like an idiot.

    It WAS a directory issue. I'd forgotten that my code was moved to a different drive with the same directory structure over the weekend.

    Thanks for all the help.

      It makes for a very interesting study in the pathology of "programmer's self-delusion", trying to reconcile this remark ("I'd forgottern that my code was moved to a different drive..."), with the remark you made about 80 minutes earlier: Yes, I added a print statement that verified I'm getting into the correct directory, and yes, the directory has "test.dat" in it.

      We all do it -- some more than others, perhaps, but no one is immune. The trick is to remember this fact, to recognize when it strikes, and to work out some ploy to circumvent the personal defect... like "Hmm, if someone else besides me were looking at this, what would they ask/look for/test..."