Recently upon browsing through some of the code and snippets posted on Perlmonks, I came across a number of nodes which performed network administration tasks. I was however dismayed to find many of these nodes used hard-coded network address, iterating through each host address, in one case, as follows:
my $subnet = "40";
for(1..239){
chomp;
my $ip = "10.1.$subnet.$_";
.
.
}
To my mind, there is a much better way to iterate through network hosts, namely, making use of the Net::Netmask module - The following subroutine of code uses this module to iterate through network hosts, the network determined by the network address and subnet mask passed as arguments to this subroutine. The network address and subnet mask passed to this subroutine can take the form of separate network block and subnet masks (eg. 192.168.1.0 and 255.255.255.0) or CIDR notation (eg. 192.168.1.0/24).
Never again should your network administration scripts be non-portable!
use Net::Netmask;
sub ips {
my $net = Net::Netmask->new(@_);
wantarray ? $net->enumerate : \@{$net->enumerate};
}