varun kumar
varun kumar

Reputation: 151

Why does the below Perl code show "Use of uninitialized value in concatenation (.) or string" when I try to use the command opendir

I was writing code to display all the files and subfolders in a directory. Is opendir and readdir only used to display files or can it display subdirectories as well?

Following is the code I am using, i don't know what I should try instead.

#!/apps/perl/5.8.9/bin/perl

use strict;
use warnings;

opendir DIR , "/home/x0280511/" || die;
while (readdir DIR) {
    print "$_\n";
}

I am getting the following error message

Use of uninitialized value in concatenation (.) or string

What exactly does the above error message mean?

Upvotes: 1

Views: 439

Answers (1)

mwp
mwp

Reputation: 8467

A bare readdir is only valid in a while-loop expression on Perl 5.12+. If you're on an earlier version of Perl, you'll need to use a different syntax to force scalar context:

while (my $ent = readdir DIR) {
  print "$ent\n";
}

Or you can use readdir in list context, just note that it will query the entire directory contents before displaying the first entry:

foreach my $ent (readdir DIR) {
  print "$ent\n";
}

Hope that helps!

Upvotes: 2

Related Questions