Ryan
Ryan

Reputation: 1050

Printing all files in a directory in Perl - will not work

So I am new to Perl and trying to simply open a directory, and list all its files. When I run this very simple code below trying to print everything in /usr/bin it will not work, and no matter what I try I keep getting told 'Could not open /usr/bin: No such file or directory'.

Any help would be much appreciated!

#!/usr/bin/perl

$indir = "/usr/bin";

# read in all files from the directory
opendir (DIR, @indir) or die "Could not open $indir: $!\n";
while ($filename = readdir(DIR)) {
    print "$filename\n";
}
closedir(DIR);

Upvotes: 0

Views: 131

Answers (1)

Sobrique
Sobrique

Reputation: 53478

Here is another place where the very basic troubleshooting step of use strict; and use warnings; has been omitted, and it would have told you exactly what was wrong.

Global symbol "@indir" requires explicit package name (did you forget to declare "my @indir"?)

Of course, you'd also have to fix a few other errors (e.g. my $indir = '/usr/bin';)

I would also suggest that readdir is not well suited for this job, and would tend to recommend glob:

#!/usr/bin/env perl
use strict;
use warnings;

my $indir = "/usr/bin";

# read in all files from the directory
foreach my $filename ( glob  "$indir/*" ) {
    print "$filename\n";
}

Note how this differs - it prints a full path to the file, and it omits certain things (like . and ..) which is in my opinion, more generally useful. Not least because another really common error is to open my $fh, '<', $filename or die $!, forgetting that it's not in the current working directory.

Upvotes: 4

Related Questions