Link to home
Start Free TrialLog in
Avatar of mikebernhardt
mikebernhardtFlag for United States of America

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);
}
ASKER CERTIFIED SOLUTION
Avatar of pwust
pwust
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tintin
Tintin

easier to just do

my @files2 = <C:/*.*>;

Open in new window


Or you can use the glob function.

my @files2 = glob('c:/*');

Open in new window

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]*");
}

Open in new window

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
Avatar of mikebernhardt

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.