Perl: how to break?

I have aa:bb::cc:yy:zz string that needs to be split so that I have an array with aa:bb::cc , yy , zz . those. I want to create two substrings from the last with : as a separator and the remaining as an element of the array. What is the best way to achieve this?

Example:

 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 save the IP address: port: protocol as a key in the file and split the ":" to get the IP, port, proto back, and everything works fine when the IP address is limited to IPv4. Now I want it to be ported to IPv6, in which case the IP address contains ":", so I can’t get the correct IP address by dividing it by ":".

+4
source share
5 answers

What 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") 
+11
source

This code will fix processing situations when $ string contains two or less pairs:

 my $string = 'aa:bb::cc:yy:zz'; my @data = split /:/, $string; if (@data > 2) { unshift @data, join ':', splice @data, 0, -2; } # $string = 'aa:bb::cc:yy:zz'; # @data contains ('aa:bb::cc', 'yy', 'zz') # $string = 'aa:bb'; # @data contains ('aa', 'bb') 
+4
source
 $ perl -wE '$_="aa:bb::cc:yy:zz"; say join "\n", split /:([^:]+):([^:]+)$/, $_;' aa:bb::cc yy zz 

Update:. You did not mention that this is for analyzing IP addresses. If so, you probably would be better off trying to find a module on CPAN

+3
source

I would make an overly aggressive split , followed by a join. I think the result is much more readable unless you use complex regex to separate. So:

 my $string = 'aa:bb::cc:yy:zz'; my @split_string = split(/:/, $string); my @result = (join(':', @split_string[0..scalar(@split_string)-3]), $split_string[-2], $split_string[-1]); print join(', ', @result), "\n"; 

Gives you:

 aa:bb::cc, yy, zz 

You will need to check the bounds of the array on @split_string before starting to index it like this.

+3
source
 $ perl -e'$_="aa:bb::cc:yy:zz"; @f=/(.*):([^:]+):(.+)/; print "$_\n" for @f' aa:bb::cc yy zz $ perl -e'$_="dd:ff:gg:dd:ee:ff:fg"; @f=/(.*):([^:]+):(.+)/; print "$_\n" for @f' dd:ff:gg:dd:ee ff fg 
+2
source

All Articles