Some one please help me: I need to perl code for a conditional block:
I believe I need to put the $email->send; command in a conditional block that checks if $duplicate_ip or $duplicate_host is defined, and then send the email. How can I do that:
use strict;
use warnings;
use MIME::Lite;
my (%ip, %host, $duplicate_ip, $duplicate_host, @linevals, $outline);
my $host_file = '/etc/hosts';
open my $file, '<', $host_file or die "can't open $host_file $!";
while (<$file>) {
chop;
if( my ($ip, $host) = /^#?([\d.]+)\s+(\S+)/ ) {
@linevals = split;
$outline = $linevals[0] . "\t" . $linevals[1] . "\n";
push @{$ip{$ip}}, $outline;
push @{$host{$host}}, $outline;
}
}
close $file;
#print "Duplicate IP's with hostnames\n";
foreach my $ip ( keys %ip ) {
if ( @{$ip{$ip}} > 1 ) {
$duplicate_ip .= join ('', @{$ip{$ip}}) . "\n\n";
}
}
#print "\nDuplicate hostnames with IP's\n";
foreach my $host ( sort keys %host ) {
if ( @{$host{$host}} > 1 ) {
my ($ip) = $host{$host}[0] =~ /^#?([\d.]+)/;
unless ( @{$ip{$ip}} > 1 ) {
$duplicate_host .= join('', @{$host{$host}}) . "\n\n";
}
}
}
my $email_msg = <<EMAIL_MSG;
The following entries in the host file are duplicates
either by IP address or by hostname.
Duplicate IP addresses:
$duplicate_ip
Duplicate Hostnames:
$duplicate_host
EMAIL_MSG
print $email_msg;
my $email = MIME::Lite->new(
From => 'xxx@xxx.com',
To => 'xxxx@xxx.com',
#Cc => 'xxx@xx.com,xxxx@att.com',
Subject => 'Host file duplicates',
Data => $email_msg
);
$email->send