PERL code snippets24 Apr 2006 01:57 pm
To determine a file's existence
# check if file exists:
CODE:
-
if (-e "filename.txt")
-
{
-
#next action
-
}
-e = existance
Filename could also be a variable as in this example
CODE:
-
$filename="test.cgi";
-
if (-e $filename)
-
{
-
#next action
-
}
Other switches;
File exists, has a size of zero: -z
File exists, has non-zero size: -s
Readable: -r
Writable: -w
Executable: -x
So, if we want to check whether we can read a file before we try to open it, we could do this:
CODE:
-
$filename="test.cgi";
-
if (-r $filename)
-
{
-
#next action
-
}
Text File: -T
Binary File: -B
They work in the same fasion
Multiple Tests
You can test for two or more things at a time using the "and" (&&) or the "or" ( || ) operators. So, if you want to know if a file exists and is readable before opening it, you could do this:
CODE:
-
$filename="test.cgi";
-
if ( (-e $filename) && (-r $filename) )
-
{
-
#next action
-
}