Check File and directory exists in Perl code example

Perl Check File and Directory exists or not in Perl example

This tutorial explains checking file or folder that exists in Perl programming with code examples.

It is very helpful before accessing files or folders in Perl.

Check File exists or not in Perl

use the -e existence operator that checks file path exists or not.

use this option in conditional statements if and print the statement.

if( -e $file){
    print("File exists");

The same way can be rewritten using a single short syntax.

print "File exists" if -f $file;

How to Check Whether Directory exists or not in Perl

To check directory exists or not in Perl, Please follow the below steps

  • Directory contains an absolute or relative path
  • If a directory is an absolute path
  • use -e and -d file text operators with a directory path that checks directory exists or not.
if( -e $directory and -d $directory){
    print("Directory exists");
  • if Directory is a relative path, you can use the File::Spec module

    • first, get the relative path using rel2abs( $relative_path )
    • join the full path using the base directory and relative path
    • Finally, Check full path is empty or not using the defined keyword

Here is an example

use File::Spec;
$fullpath = File::Spec->rel2abs( $relative_path ) ;
$fullpath = File::Spec->rel2abs( $relative_path, $directory ) ;
if ( defined $fullpath ) {
    print "\n folder exists ";

Check if directory exists in ~/ in Perl

The ~ bash symbol, represents the user’s home directory.

use the -d file test operator to check home directory exists or not

use strict;
my $directory="~/work";
if ( -e $directory and -d directory) {
    print "Home directory exists \n";
else {
    print "Home directory does not exist \n";

Similarly, In Perl, you can get the user home directory using the $ENV{HOME} variable

use strict;
my $directory="$ENV{HOME}/work";
if ( -e $directory and -d directory) {
    print "Home directory exists \n";
else {
    print "Home directory does not exist \n";

How to open a file only if it already exists?

check -e file equality operator to check file exists or not, Next, read the file using open and >> syntax.

Use the above logic in the conditiona if statement.


if (-e $file_name and open my $file, '>>', $file) {
  # File exists and reads the file
} else {
  # file does not exist and not read
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.