Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 214
  • Last Modified:

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);
}
0
mikebernhardt
Asked:
mikebernhardt
1 Solution
 
pwustCommented:
The way parameters is passed to Perl functions is different:

$MyDir = "c:\\";
(@files2) = OPENDIR ($MyDir);
print join("\n",@files2);

sub OPENDIR {
$dir = $_[0];
opendir (THEDIR, $dir) or die "can't open directory $dir";
while (defined(my $filelist = readdir(THEDIR))) {
      push (@files,$filelist);
}
closedir (THEDIR);
return (@files);
}

Open in new window

0
 
TintinCommented:
easier to just do

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

Open in new window


0
 
FishMongerCommented:
Or you can use the glob function.

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

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
FishMongerCommented:
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

0
 
ozoCommented:
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
0
 
mikebernhardtAuthor Commented:
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.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now