nims nims - 2 months ago 20
Perl Question

string comparison in foreach



The below test is to check the software information on a list of IP addresses.
The program prints the version of software running on all the IPs as expected.

Now, I would like to test whether the software running on all the IPs are identical? How do I do that?

sub test_check_software_info_on_all_the_ips {

my ($self) = @_;

$self->{'machine_ip'} = $self->{'queryObj'}->get_machine_ip();

foreach my $ip ( @{ $self->{'machine_ip'} } ) {

$self->{'install_info'} = $self->{'queryObj'}->get_install_info($ip);

INFO( 'Software info of ' . $ip . ' is ' . $self->{'install_info'} );
}
}


Sample output

20160907T141846 INFO Software info of 1.1.1.1 is r-2016-08-27-03
20160907T141846 INFO Software info of 2.2.2.2 is r-2016-08-27-03
20160907T141847 INFO Software info of 3.3.3.3 is r-2016-08-27-03
20160907T141847 INFO Software info of 4.4.4.4 is r-2016-08-27-03

Answer

This will do as you ask

sub check_matching_info {

    my ($self) = @_;

    my $ips = $self->{queryObj}->get_machine_ip;

    my %info;

    for my $ip ( @$ips ) {
        my $info = $self->{queryObj}->get_install_info($ip);
        push @{ $info{$info} }, $ip;
    }

    print keys %info == 1 ? "All IPs have the same install info" : "IPs have different install info";
}
Comments