Checking if filename exists in current directory

648 Views Asked by At

I have a script that I am trying to modify so that depending on the location its executed from, it will be checking to see if there is a file with the name regression_user.rpt and if so, it will make a new file called regression_user1.rpt. I've found solutions but Im not sure how to change it to do what I want.

What I have is the following:

my $filename = 'c:\temp\test.txt';
if(-e $filename){
   //Create file with new name
   print("File $filename exists\n");
}else{
   //Create base file
   print("File $filename does not exists\n");
}

Except, the path for $filename is variable. Is there a way to incorporate the execution location as a variable into this check?

The purpose of this is to make sure I dont overwrite existing files (has happened one too many times).

1

There are 1 best solutions below

2
ikegami On BEST ANSWER

If by execution location you mean the current work directory, all you need is the following:

my $filename = 'test.txt';

If by execution location you mean the directory in which the script being executed is found, you can use the following:

use FindBin qw( $RealBin );

my $filename = "$RealBin/test.txt";