Perl one liner to extract first three octets of IP Address

Hi

I have an inherited perl script that extracts the first three octets of an IP Address using a combination of split() against a dot and then builds it all back together again, its a whole block of code to do this

I wondered if anyone had a one liner in their arsenal to extract the first three octets into a variable ?

Cheers

My perl is non-existent, but you might use this regex:

sed 's/\.[^.]*$//' file

Thanks, so within my perl script I can invoke shell (cheating a bit) to get the result

my $firstthree = `echo $ip | sed -e 's/\.[^.]*\$//'`;
chomp $firstthree;

Which returns the desired result

But id love to know how to do this natively in perl without having to invoke a shell process

You know you can use regexes in perl as well, do you?

$ip="10.20.30.40";
$ip=~s/\.[^.]*$//;
printf "%s\n", $ip;

Or with split

$ip="10.20.30.40";
($a1,$a2,$a3)=split(/\./,$ip);
printf "%s\n", join ".",$a1,$a2,$a3

Or, just using shell built-ins, assuming that there are 4 period separated parts of your input ip address and you want to output the 1st three:

$ ip=w.x.y.z
$ echo ${ip%.*}
w.x.y
$ 

Please, try in Perl

my ($mask) = $ip =~ /^(\d+\.\d+\.\d+)/;

thanks