glob - Perl - A way to get only the first (.txt) filename from another directory without loading them all? -


i have directory holds ~5000 2,400 sized .txt files.

i want 1 filename directory; order not matter.

the file processed , deleted.

this not scripts working directory.

the intention is:

  • to open file,
  • read it,
  • do stuff,
  • unlink , then
  • loop next file.

my crude attempt not check .txt files , has ~5000 filenames 1 filename. possibly calling many modules?

the verify_empty sub intended validate there directory , there files in but, attempts failing so, here seeking assistance.

#!/usr/bin/perl -w use strict; use warnings; use cgi; use cgi ':standard'; print cgi::header(); use cgi::carp qw(fatalstobrowser warningstobrowser); ### use vars qw(@files $thefile $pathtofile); $listfolder = cgi::param('openthisfolder'); get_file($listfolder); ### sub get_file{   $listfolder = shift;   unless (verify_empty($listfolder)) {     opendir(dir,$listfolder);     @files = grep { $_ ne '.' && $_ ne '..' } readdir(dir);     closedir(dir);     foreach(@files){       $thefile = $_;     }     #### go off process , unlink file (sub not here) ####     $pathtofile = $listfolder.'/'.$thefile;     openfilereadprepare($pathtofile);      #### after unlinked, openfilereadprepare sub loops script.    }   else {     print qq~no more files process~;     exit;   }   exit; }     #### sub verify_empty {   $listfolder = shift;   opendir(dir, $listfolder) or die "not directory";   return scalar(grep { $_ ne "." && $_ ne ".." } readdir(dir)) == 0;   closedir(dir); } 

obviously new @ this. method seems quite "hungry"? seems lot grab 1 filename , process it! guidance great!

edit -latest attempt

my $dir = '..'; @files = glob "$dir/*.txt"; (0..$#files){ $files[$_] =~ s/\.txt$//; } $pathandfile =$files[0].'.txt'; print qq~$pathandfile~; 

this "works" but, still gets filenames. none of examples here, far, have worked me. guess live today until figure out. perhaps revisit , see if came better.

you loop using readdir inside while loop. in way readdir won't return files give 1 @ time,

# opendir(dir, ...); $first_file = ""; while (my $file = readdir(dir)) {    next if $file eq "." or $file eq "..";   $first_file = $file;   last; } print "$first_file\n"; # first file in directory 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -