http://www.perlmonks.org?node_id=994359


in reply to replacing the last portions of an octet

Here were two functions I wrote (before I found out about things like Net::IP or NetAddr::IP that you might find helpful:

sub dq2number { my $ip = shift; return unpack "N", pack "C4", split /\D/, $ip; } sub number2dq { my $n = shift; return join q{.}, unpack "C4", pack "N", $n; }

Here is an example, so you can see the result

use strict; use warnings; my @c = qw/ 0.0.0.0 0.255.255.255 10.0.0.1 172.16.0.1 127.0.0.1 192.168.0.1 /; foreach my $d (@c) { print $d, q{ }, number2dq( dq2number( $d ) - 1 ), q{ }, number2dq( dq2number( $d ) + 1 ), qq{\n}; } sub dq2number { my $ip = shift; return unpack "N", pack "C4", split /\D/, $ip; } sub number2dq { my $n = shift; return join q{.}, unpack "C4", pack "N", $n; } # Output: # 0.0.0.0 255.255.255.255 0.0.0.1 # 0.255.255.255 0.255.255.254 1.0.0.0 # 10.0.0.1 10.0.0.0 10.0.0.2 # 172.16.0.1 172.16.0.0 172.16.0.2 # 127.0.0.1 127.0.0.0 127.0.0.2 # 192.168.0.1 192.168.0.0 192.168.0.2

Hope that helps.