mikebernhardt
asked on
How do I make this simple function work?
The goal is to pass the name of a directory to a function which opens the directory, creates a list of files and returns that list back where I print the list. The function works just fine if I change $dir to directly use $MyDir so for some reason the directory name isn't being passed to the function and it can't open the directory.
Not sure what I'm doing wrong but I'm sure it's simple. Help greatly appreciated!
$MyDir = "c:\\";
(@files2) = OPENDIR ($MyDir);
print join("\n",@files2);
sub OPENDIR ($dir){
opendir (THEDIR, $dir) or die "can't open directory $dir";
while (defined(my $filelist = readdir(THEDIR))) {
push (@files,$filelist);
}
closedir (THEDIR);
return (@files);
}
Not sure what I'm doing wrong but I'm sure it's simple. Help greatly appreciated!
$MyDir = "c:\\";
(@files2) = OPENDIR ($MyDir);
print join("\n",@files2);
sub OPENDIR ($dir){
opendir (THEDIR, $dir) or die "can't open directory $dir";
while (defined(my $filelist = readdir(THEDIR))) {
push (@files,$filelist);
}
closedir (THEDIR);
return (@files);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Or you can use the glob function.
my @files2 = glob('c:/*');
If you wanted/needed to use a subroutine for this, then here's a minimal example.
my $dir = 'C:/';
my @files2 = get_files($dir);
print "$_\n" for @files2;
sub get_files {
return glob("$_[0]*");
}
the difference between
sub get_files {
return glob("$_[0]/*");
}
and
sub get_files {
my $dir = shift;
opendir (THEDIR, $dir) or die "can't open directory $dir";
my @files= readdir(THEDIR);
closedir (THEDIR);
return @files;
}
is that the glob will include the $_[0] path in the returned list, while the readdir will not
sub get_files {
return glob("$_[0]/*");
}
and
sub get_files {
my $dir = shift;
opendir (THEDIR, $dir) or die "can't open directory $dir";
my @files= readdir(THEDIR);
closedir (THEDIR);
return @files;
}
is that the glob will include the $_[0] path in the returned list, while the readdir will not
ASKER
Thanks guys. The example script I posted was part of something much bigger. Although you all had good ideas, passing the reference properly was what I needed to know to move on with my project.
Open in new window