By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,847 Members | 2,285 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,847 IT Pros & Developers. It's quick & easy.

Printing a "File Not Found" message in Perl.

P: 32
Hi - I know almost nothing about Perl but do program in other languages. I am looking at Perl that I have to modify slightly by printing a "file not found" message if a file is missing from the directory or the directory just above it (hence the 'find ..' ). Please help!

Expand|Select|Wrap|Line Numbers
  1. sub findText
  2. {
  3.   my @aray = 'find .. -name veryImprotant.txt -print';
  4.   my $var = shift @aray;
  5.   # I want to check if file is not found here maybe?
  6.   return $var;
  7. }
Jul 10 '09 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 410
While running system commands, pass the command within reverse quotes( ` ). You have used single quotes, hence the command will not be run (it is passed as a string).

Expand|Select|Wrap|Line Numbers
  1. sub findText 
  2.   my @aray = `find .. -name veryImprotant.txt -print`; 
  3.   my $var = shift @aray; 
  4.   print "File not found \n" unless($var);
  5.   return $var; 
Jul 28 '09 #2

Expert Mod 2.5K+
P: 3,503
Personally, I would take a different route. I would actually use the open() function to open the file and die if it didn't work. If it opened, make a log entry into a log and then close the file.

Expand|Select|Wrap|Line Numbers
  1. sub findText {
  2.     open(FILE, "../veryImportant.txt") or die "Cannot open file:  $!";
  4.     print LOG "File: veryImportant.txt exists.  Continuing.";
  6.     close(<FILE>);
  7. }
Yes, the log file represented by the LOG file handle will have had to be previously opened, but that is no biggie. My point was to show you another way of doing it that didn't involve executing a system command. This, btw, would possibly work on Unix, Linux and maybe even Windows due to the lack of system level command execution.


Jul 28 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.