Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 292
  • Last Modified:

perl, how to find out if a file exist

In perl, how do I check if a file exist?
#if file exist, print message
0
rgbcof
Asked:
rgbcof
  • 4
  • 2
  • 2
  • +1
2 Solutions
 
jeromeeCommented:
Check this out: http://perldoc.perl.org/functions/-X.html

my $myfile = "/tmp/test.txt";
if( -e $myfile ) {
    print "$myfile exists\n";
} else {
    print "$myfile does not exist\n";

}

Open in new window

0
 
rgbcofAuthor Commented:
It works.  Thanks.
0
 
nemws1Database AdministratorCommented:
joremee is correct - you want the '-e' option.  The only change I'd make to his code is to put double-quotes around the file argument in line 2 (in case it has a space or other odd character):
if( -e "$myfile" ) {

Open in new window

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
rgbcofAuthor Commented:
It works.  Thanks
0
 
jeromeeCommented:
Hi nemws1,
This script being a perl script, I don't believe that the double quotes are required.
Please correct me if I'm wrong.
0
 
ozoCommented:
the quotes are not required
0
 
jeromeeCommented:
Thanks Ozo.
I thought I was going crazy for a sec.
0
 
nemws1Database AdministratorCommented:
I should have been more clear - my apologies, jeromee.  No, quotes are not required for a single scalar argument.  The problem is that people get in the habit of doing it this way and then they write something like this:
 
$p="/home/user"
$f="datafile"
if (-e $p/$f) {
   .....
}

Open in new window

Which is obviously incorrect.  IMO, it is good coding habit (and also helps with readability) to put double quotes around files/paths.  Saves you many a headache.
0
 
ozoCommented:
on the other hand, if people get in the habit of using unnecessary quotes
they may write something like this:

open $myfile,"/tmp/test.txt" or die;
if( -e "$myfile" )

which is not so obviously incorrect.
0
 
jeromeeCommented:
No apologies req'd nemws1.
Thanks anyway.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now