I want to be able to send an email if the contents of a variable are not empty
this is my code:
my $output = $ssh->capture({stdin_data => <<'EOS'}, 'pfexec /usr/bin/perl');
use File::Find::Rule;
my $dir = '/dir';
my $today = time();
my $onehour = $today - (60*60);
my $oneday = $today - (24*60*60);
my @files = File::Find::Rule->file()
->name("*.0")
->mtime(">$oneday")
->mtime("<$onehour")
->in( "$dir" );
for my $file (@files) {
print "$file\n";
}
EOS
sub send_email{
use MIME::Lite;
$to = 'abcd@gmail.com';
$cc = 'efgh@mail.com';
$from = 'webmaster@yourdomain.com';
$subject = 'Test Email';
$msg = MIME::Lite->new(
From => $from,
To => $to,
Cc => $cc,
Subject => $subject,
Data => $output
);
$msg->send;
}
if ($output) {
send_email($output);
}
as you can see i connect remotely to a server. find a few files and if files are found send them by email.
I do not know how to create the subroutine so it takes the $output
as parameter and sends it by mail.
thanks
So you're asking how subroutines receive parameters? It's through the @_
array. I did a little rewrite of your sub below.
Note: use Mime::Lite;
should move outside the sub...it's probably best to move it all the way to the top. All use
modules is always runned first anyway, no matter where it's at in your code, so it might as well be listed close to the top. Also, it's often useful to view all dependencies at one place. On the slight chance you absolutely don't want to load the Mime::Lite module unless send_email is called, use require Mime::Lite;
instead of use
inside the sub, it will then be included the first time the sub is called.
Remember to use my
for local vars so you don't get trouble with others vars using the same name as your program grows (known as namespace pollution)
use MIME::Lite;
...
my $output = $ssh->capture( ... );
...
sub send_email {
my($data) = @_;
my $subject = 'Test Email';
my($to,$cc,$from) = ('abcd@gmail.com',
'efgh@mail.com',
'webmaster@yourdomain.com');
my $msg = MIME::Lite->new(
From => $from,
To => $to,
Cc => $cc,
Subject => $subject,
Data => $data,
);
$msg->send;
}
send_email($output) if $output;