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

I use glob to find a txt file in a directory "files",I want to be glob free,because perlglob needs to be installed,how do I change the below line to remove glob?

$file = glob(($dir . '\\files\\*.txt'));

Replies are listed 'Best First'.
Re: Removing glob
by ikegami (Patriarch) on Feb 18, 2011 at 19:54 UTC

    Keep in mind that glob($dir . '\\files\\*.txt'); will fail if $dir includes characters special to glob, such as space.

    You'd be better off using bsd_glob from File::Glob directly instead of using it via glob. Then, spaces won't be a problem. Other special characters won't cause any harm since they're not found in file names.

    There's also the issue that glob acts very specially in scalar context. If you want the first file returned by glob, use ($file)= instead of $file=. If you don't, subsequent calls to glob will return "odd" results.

      Simply using real slashes, ie glob "$dir/files/*.txt" tends to work regardless of spaces

        No:

        c:\windows\system32>perl -wle "print for glob shift" "C:/Program Files +/*" C:/Program

        Using File::Glob::bsd_glob works as it should:

        c:\windows\system32>perl -MFile::Glob=bsd_glob -wle "print for bsd_glo +b shift" "C:/Program Files/*" C:/Program Files/HP

        ... but the direction of slashes does not matter:

        c:\windows\system32>perl -MFile::Glob=bsd_glob -wle "print for bsd_glo +b shift" "C:\Program Files\*" C:\Program Files\HP
Re: Removing glob
by Corion (Patriarch) on Feb 18, 2011 at 19:28 UTC

    I think perlglob does not need to be installed for using glob since Perl 5.6. What OS and Perl are you using that glob does not work there?

Re: Removing glob
by toolic (Bishop) on Feb 18, 2011 at 18:53 UTC
    File::Slurp
    use warnings; use strict; use File::Slurp; my @files = map { "$dir/$_" } grep { -f "$dir/$_" and /^files.*\.txt$/ + } read_dir($dir);
Re: Removing glob
by wind (Priest) on Feb 18, 2011 at 18:46 UTC
    use File::Spec; use strict; my $dir = '/foo/bar'; my $filesdir = File::Spec->catdir($dir, 'files'); my $file = ''; opendir my $dh, $filesdir or die "Can't opendir, $filesdir: $!"; while (readdir $dh) { if (/\.txt$/) { $file = $_; last; } } print $file . "\n";