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

i read the file name in a directory with opendir and readder, example:
my $dir = "c:/temp/"; opendir (DIR, $dir) or die "Unable to open dir $dir : $!"; my @files = readdir(DIR) or die "Unable to readdir $dir : $!"; closedir DIR; print "@files <br>";
Now, i would like to read only the file name that begin with xxxx

Can you help me with an example ??

Thank you
Claudia

edit (broquaint): added <code> tags + formatting

Replies are listed 'Best First'.
Re: readdir
by Zaxo (Archbishop) on Oct 30, 2002 at 08:05 UTC

    For another approach, you can try:

    # my @files = <c:/temp/xxxx*>; # or better my @files = glob 'c:/temp/xxxx*';

    Untried on win32, but should work.

    After Compline,
    Zaxo

Re: readdir
by grantm (Parson) on Oct 30, 2002 at 08:10 UTC

    Instead of opendir+readdir you could just use glob():

    my @files = glob("C:/Temp/xxxx*");

    Another way of saying this is to use the <pattern> globbing operator:

    my @files = <C:/Temp/xxxx*>;

    But as BrentDax kindly pointed out, the first form is probably less confusing.

    Update: Zaxo beat me to the draw - my posting took longer to prepare since I was testing my code on Win32 :-)

Re: readdir
by djantzen (Priest) on Oct 30, 2002 at 07:03 UTC

    i would like to read only the file name that begin with xxxx

    Um, you want to read the file names without reading them? Perhaps this would be more helpful ;)

    Okay, perhaps you mean that you want to return only those files whose titles match 'xxxx'. Try:

    my @new_files = grep $_ =~ /^xxxx/, @files;

    This will grep the list, setting $_ equal to each element in @files, and looking for matches that begin with the string you want. Then you can resume your processing, presumeably reading only those files.

    HTH.

Re: readdir
by dingus (Friar) on Oct 30, 2002 at 12:05 UTC
    Other people have suggested various ways of GLOBbing. Here's a trick for when you want to do the same thing for the exact directory tree. (Using DOSGLOB because c:/temp/ - regular GLOB should also work). The Regex used for the compare uses the greediness thing to match everything up to the last / in the .*

    use File::DosGlob; $fn = 'c:/temp/*'; my @m = File::DosGlob::doglob(1,$fn); for (@m) { push @m, $_.'/*' if -d($_); # if directory add contents to end of Arra +y if (m!^.*/xxxx!) { # if filename starts with xxxx do_something_with($_); } }
    Share and Enjoy
    Dingus
      sorry cut and pasted the broken script. This is better
      use File::DosGlob; $fn = 'c:/temp/*'; my @m = File::DosGlob::doglob(1,$fn); for (@m) { # if directory add contents to end of Array push @m, File::DosGlob::doglob(1,$_.'/*') if -d($_); if (m!^.*/xxxx!) { # if filename starts with xxxx do_something_with($_); } }