开发者

perl : how to split?

I have a string aa:bb::cc:yy:zz开发者_C百科 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 ":".


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")


This code will correct handle situations when $string contains 2 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')


I'd do an overly aggressive split followed by a join. I think the result is much more readable when you're not using a complicated regex for the split. 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'd have to do some array bounds checking on @split_string before you start indexing it like that.


$ perl -wE '$_="aa:bb::cc:yy:zz"; say join "\n", split /:([^:]+):([^:]+)$/, $_;'
aa:bb::cc
yy
zz

Update: You did not mention this was meant to parse IP addresses. If it is, you would probably be better off trying to find a module on CPAN


$ 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜