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

I want to list the contents of a directory into an array; however, I want to only list the filename without listing which directory it is in or the extension.
  • Comment on Contents of directory without extensions

Replies are listed 'Best First'.
Re: Contents of directory without extensions
by data64 (Chaplain) on Nov 25, 2001 at 05:11 UTC
    I am filtering out any directories. Not sure if you need it.
    #the pragmas, sorted alphabettically use diagnostics; use strict; use warnings; #the imported packages use English; use File::Spec::Functions; use File::Basename; # check if directory specified, else assumer current directory my $dir = ( scalar(@ARGV) > 0 ) ? $ARGV[0] : curdir(); my ( @files, $file, @files_wo_extn ); opendir( DIR, $dir ) or die "Could not open $dir, $OS_ERROR"; @files = readdir(DIR) or die "Reading entries in $dir, $OS_ERROR"; closedir(DIR); foreach $file (@files) { #check whether the file is a directory #need to use the directory and file to access the file unless ( -d catfile( $dir, $file ) ) { push @files_wo_extn, basename($file); } } print join "\n", @files_wo_extn; print "\n";
    • Why not use File::Find?
    • English is bad especially if not invoked as: use English qw( -no_match_vars );
    • You provide no argument to basename and thus do not remove extensions
    • use File::Basename; use File::Find; use vars '@listOfFiles'; find(sub{ return if -d $File::Find::name; #Remove last extension only... remove '?' to be greedy push @listOfFiles, (fileparse($File::Find::name, qr(\..+?)))[ +0]; }, '/path/of/least/resistance');

      --
      perl -p -e "s/(?:\w);([st])/'\$1/mg"

        You are right, I need to use fileparse instead of basename.
        What's with the -no_match_vars for use English;. I don't see that in the docs.