链接:
Using split() to divide a string by length
Re: Using split() to divide a string by length by Zaxo on Apr 13, 2006 at 19:39 UTC Another trick that works is to capture the split characters, which places them also in @fields and makes pos advance beyond them. Since all but probably the last group match, the normal split results mostly don't contain anything, so we need to filter out false elements with grep:After Compline, Zaxo代码: 全选
my $string = join '', a..z; my @fields = grep {$_} split /(.{3})/, $string; print "@fields\n"; __END__ abc def ghi jkl mno pqr stu vwx yz
Re: Using split() to divide a string by length by BrowserUk on Apr 13, 2006 at 20:08 UTC I find unpack more suitable for this task.扩展后是这样的:Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error. Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal? "Science is about questioning the status quo. Questioning authority". In the absence of evidence, opinion is indistinguishable from prejudice.代码: 全选
print for unpack '(A3)*', "abcdefghi";; abc def ghi
代码: 全选
for (unpack '(A3)*', "abcdefghi")
{
print $_, "\n";
}
Re: Using split() to divide a string by length by chibiryuu on Apr 13, 2006 at 20:10 UTC This doesn't use split, but is the first thing I think of:Hmm, $string =~ /.{1,3}/g should even be faster than split /(?(?{pos() % 3})(?!))/, $string. I guess not as fast as unpack, though.代码: 全选
my $string = join '', 'a'..'z'; my @fields = $string =~ /.{1,3}/g; my @fields2 = grep {$a=!$a} @fields;