1

If I had

my $ip = "10.9.8.X";

and I want $IPCore to have "10.9.8". Is there an easy way to do this in a single line?

I usually do this

my $ip = "10.9.8.X";
my $IPCore = $ip;
$IPCore =~ s/([0-9]{3}\.[0-9]{3}\.[0-9]{3})\.[xX]{1,3}$/$1/

##$IPCore is now 10.9.8

Is there an easier way to do this?

Thank you

3 Answers 3

2

Short solution to remove the last . and everything after it:

( my $IPCore = $ip ) =~ s/\.[^.]*\z//;
my $IPCore = $ip =~ s/\.[^.]*\z//r;                        # 5.14+

Optimized solution to remove the third . and everything after it:

( my $IPCore = $ip ) =~ s/^[^.]*+(?:\.[^.]*+){2}\K.*//s;   # 5.10+
my $IPCore = $ip =~ s/^[^.]*+(?:\.[^.]*+){2}\K.*//sr;      # 5.14+
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you trust the IPs will come in a reasonable format, a really simple approach is just to cut off the last segment from the last .(dot) like so:

 my $ip = '10.9.8.x';
 (my $ipCore = $ip) =~ s/(.*?)\.[^.]+$/$1/;
 print $ipCore;
//yields '10.9.8'

Comments

0

3 birds, 1 stone

my ($ip, $IPCore) = ("10.9.8.X");
print $IPCore if $ip =~ /([0-9]{1,3}(?:\.[0-9]{1,3}){2})\.[xX]{1,3}$(?{$IPCore=$^N})/;

Out 10.9.8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.