Search code examples
arraysperlglobpopulate

perl populating arrays with filenames from user defined directory?


I'm trying to populate two arrays with filenames from a user defined directory. The code I have so far works if the files are in the same directory where I'm running the program. The ultimate goal of this code is to convert a file from one format to another using a script, and exporting the newly converted files into a user defined directory.

# Get export directory
my $export_dir = $ARGV[0]."\\";

print "Export Directory: \"$export_dir\"\n\n" if DEBUG;

# Get current working directory
my $cwd_dir =  getcwd;

# Replace slashes with back-slashes for Windows compatibility
$cwd_dir =~ s/\//\\/g;

print "Current Working Directory: \"$cwd_dir\"\n\n" if DEBUG;


# Get list of ZIP files in directory
my @zip_files = glob "*.zip";

This code works when the zip files are in the current working directory. How do I get it to work where the zip files are in a user defined directory? (In this case a subfolder, but should be wherever the user defines the export directory).


Solution

  • Simply pre-pend the directory name to a glob spec:

    my @zip_files = glob "$export_dir\\*.zip";
    

    P.S. Ideally, you should use File::Spec CPAN module to construct file paths in OS-independent way, instead of hard-coding "\\" for Windows and "/" for Unix.