By "arguments to a subroutine", I'm referring to passing a special value that the subroutine could match against to determine what it should do. For example, below is a quick attempt to pull out your e-mail handling and move it to a separate function, along with how I might call it.
Here's where I would be making use of the function, which I called
send_mail() just to stick with what I'd used previously:
open( my $fh, "<", $array_ip_list )
or send_mail("ip_list_error"),
die "IP List File - nas_array_ip_list.txt not found";
# [ . . . Do lots of stuff here . . . ]
# If our external commands completed successfully, send our e-mail
if ($result_from_nas_check_function) {
send_mail( "results", $filename );
# [ Clean up after ourselves, delete our temp file, etc. ]
exit 0;
}
else {
# [ Notify e-mail that an error occured ]
# [ Clean up after ourselves, delete our temp file, etc. ]
die "Something went wrong.";
}
And here's an example of how I might define the send_mail() function, where I tell it what kind of e-mail it is sending, and then let it do the work:
# Expects at least 1 argument matching the type of e-mail to send, and
# optionally the additional arguments it might need. If this got much
# more complicated, it might be worth passing the second argument as a
# hash to simplify multiple values coming in.
sub send_mail {
# These could go at the beginning of your script, I just put them
# here to make this a more complete example.
use MIME::Lite;
MIME::Lite->send( "smtp", "mail.server.com" );
my $type = shift; # what type of message should we send?
my @args = @_;
my $from = 'foo@example.com';
my $to = 'bar@example.com';
my $msg;
if ( $type eq "ip_list_error" ) {
$msg = MIME::Lite->new(
From => $from,
To => $to,
Data => "Error:nas_array_ip_list.txt:$!.$
+^E\n",
Subject => "IP List File - nas_array_ip_list
+.txt - "
. "Not Found For $0 Script on $ENV{COMPUTE
+RNAME}\n",
);
}
elsif ( $type eq "results" ) {
my $filename = $args[0];
$msg = MIME::Lite->new(
From => $from,
To => $to,
Subject => "Automated Check For NAS DataMover Health.",
Type => 'Multipart/mixed',
);
$msg->attach( Type => 'TEXT',
Path => $filename,
Filename => $filename,
Disposition => 'inline', );
}
else {
die "send_mail - bad type: $type\n"
}
# This will send our e-mail, regardless of which one we built.
$msg->send;
}
Update: Added the final else, thanks to wfsp's excellent suggestion.