Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl : how to split?

I have a string aa:bb::cc:yy:zz which needs to be split in such a way that I have an array with aa:bb::cc, yy, zz. i.e. I want to create two substrings from last with : as delimiter and remaining as a element of an array. What's the best way to achieve this?

ex:

aa:bb::cc:yy:zz --> ['aa:bb::cc','yy','zz']

dd:ff:gg:dd:ee:ff:fg --> ['dd:ff:gg:dd:ee','ff','gg']

I store IP address:port:protocol as a key in a file , and splitting wiht ":" to get IP,port,proto back and things were working fine when IP address is limited to Ipv4. Now I want to make it ported to Ipv6 in which case IP address contains ":" so I can't get proper IP address by splitting with ":".

like image 584
kumar Avatar asked Nov 29 '22 17:11

kumar


1 Answers

How about:

#!/usr/local/bin/perl 
use Data::Dump qw(dump);
use strict;
use warnings;

my $x = 'dd:ff:gg:dd:ee:ff:fg';
my @l = $x =~ /^(.*?):([^:]+):([^:]+)$/g;
dump @l;

output:

("dd:ff:gg:dd:ee", "ff", "fg")
like image 132
Toto Avatar answered Dec 04 '22 16:12

Toto