There are two modules which I think you should have a look at -
Net::CIDR and more importantly,
Net::Netmask. The latter of these modules incorporates a number of functions for exactly what you are requiring. eg.
use Net::Netmask;
my ($block) = new Net::Netmask ("192.168.1.5", "255.255.255.0");
print $block->base(), "/", $block->bits(), "\n";
Ooohhh, Rob no beer function well without!