I've written a script to traverse my web server, find any files called 
"error_log", e-mail them to me, and then delete them.  It is triggered by cron 
twice a day.

        The script works great but I'd like to get advice on how I can clean up 
my code, so any comments are welcome.

        Also, do I really need the foreach block in there?  I couldn't get it 
to work without it, but it seems like I should be able to. =:\

Thanks,
Marc

------------------------------------

#!/usr/bin/perl

use strict;
use warnings;

use File::Find;
use File::HomeDir;

my $path_to_search = File::HomeDir->my_home.'/public_html';
my $file_name      = 'error_log';
my $from_address   = 'x...@xxx.com';
my $to_address     = 'x...@xxx.com';
my $mail_app       = '/usr/sbin/sendmail';
my $subject        = 'An "error_log" was found';

find(\&wanted, $path_to_search);

sub wanted {
        if ($File::Find::name =~ /$file_name/) {
                my $msg = "MIME-Version: 1.0\n".
                                  "Content-Type: text/plain\n".
                                  "To: $to_address\n".
                                  "From: $from_address\n".
                                  "Subject: $subject\n\n";

                open (my $mail_fh, "|$mail_app -t -oi -oem") || die "Can't open 
sendmail!";
                        print {$mail_fh} "$msg";
                        print $msg;
                        open (my $file_fh, '<', $File::Find::name) || die 
"Can't open $file_name: $!";
                                my (@lines) = <$file_fh>;
                                foreach my $line (@lines) {
                                        print "$line";
                                }
                                print {$mail_fh} "@lines";
                        close ($file_fh) || die "Can't close file";
                close $mail_fh || die "Can't close mail_fh";
                unlink ($File::Find::name);
        }
}

----------------------------

In case anyone's interested, here's the shell script it replaces:

#!/bin/sh

## Variables ##
FILES=`find /home/user/public_html -name error_log`
ADDRESS=x...@xxx.com

for file in $FILES
  do
    if [ -e "$file" ]
    then
      mail -s "$file" $ADDRESS < $file
      rm -r $file  # delete log file
    fi
  done


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to