prgrm
prgrm

Reputation: 3833

Checking if a directory exists with Perl

I am trying to check if a directory exists in a UNIX system with Perl.

while (my @row = $sth->fetchrow_array) {
    my $id = $row[0];
    my $hash = $row[1];
    my $direction = '/home/users/' . $hash

    if(-d $direction){
        print "$direction exists";
    }

}

But I get this error:

Global symbol "$direction" requires explicit package name at Perl.pl line 31. syntax error at Perl.pl line 31, near "){" syntax error at Perl.pl line 35, near "}" Execution of Perl.pl aborted due to compilation errors.

Line 31 in this case is:

if(-d $direction)

Any ideas?

Upvotes: 0

Views: 1050

Answers (2)

ikegami
ikegami

Reputation: 385655

If you ever get a syntax error at the start of the BLOCK (near ") {") of an if, unless, while, until, for, foreach or when statement, check if the previous statement is missing its semi-colon (;).

Similarly, if you ever get a syntax error at the semi-colon (near "<something>;") of a C-style for statement (for (...; ...; ...;) { ... }), check if the previous statement is missing its semi-colon (;).


If you mean to write

f();
if (g()) { h() }

but you write

f()
if (g()) { h() }

Perl thinks you're missing a semi-colon before the BLOCK

f()
if (g()) HERE { h() }

because the following is valid Perl:

f() if (g())

Upvotes: 4

Russell Shingleton
Russell Shingleton

Reputation: 3196

my $direction = '/home/users/' . $hash

This line is missing a semi-colon, causing a compile error.

Upvotes: 5

Related Questions