JohnnyLoo JohnnyLoo - 5 months ago 7
Perl Question

Assign section of variable to another variable in Perl using regexp

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

Answer

Short:

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

Optimized:

( my $IPCore = $ip ) =~ s/^(?:[^.]*+\.){3}\K.*//s;   # 5.10+
my $IPCore = $ip =~ s/^(?:[^.]*+\.){3}\K.*//sr;      # 5.14+
Comments