Connecting Tech Pros Worldwide Forums | Help | Site Map

Printing a "File Not Found" message in Perl.

Newbie
 
Join Date: Apr 2009
Posts: 5
#1: Jul 10 '09
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. }
  8.  

nithinpes's Avatar
Expert
 
Join Date: Dec 2007
Posts: 402
#2: Jul 28 '09

re: Printing a "File Not Found" message in Perl.


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; 
  6.  
numberwhun's Avatar
Site Moderator
 
Join Date: May 2007
Location: New Hampshire, USA
Posts: 2,640
#3: Jul 28 '09

re: Printing a "File Not Found" message in Perl.


Quote:

Originally Posted by dissectcode2 View Post

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. }
  8.  

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:  $!";
  3.  
  4.     print LOG "File: veryImportant.txt exists.  Continuing.";
  5.  
  6.     close(<FILE>);
  7. }
  8.  
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.

Regards,

Jeff
Reply