[转][Perlmonks]字符串等长划分的N种方法

There's more than one way to do it!
https://metacpan.org http://perlmonks.org
回复
头像
523066680
Administrator
Administrator
帖子: 573
注册时间: 2016年07月19日 12:14
联系:

[转][Perlmonks]字符串等长划分的N种方法

帖子 523066680 »

_
链接:
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:

代码: 全选

    my $string = join '', a..z;

    my @fields = grep {$_} split /(.{3})/, $string;

    print "@fields\n";

    __END__
    abc def ghi jkl mno pqr stu vwx yz
After Compline, Zaxo
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.

代码: 全选

    print for unpack '(A3)*', "abcdefghi";;
    abc
    def
    ghi
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.
扩展后是这样的:

代码: 全选

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:

代码: 全选

    my $string = join '', 'a'..'z';
    my @fields = $string =~ /.{1,3}/g;
    my @fields2 = grep {$a=!$a} @fields;
Hmm, $string =~ /.{1,3}/g should even be faster than split /(?(?{pos() % 3})(?!))/, $string. I guess not as fast as unpack, though.
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 4 访客