使用perl脚本获取字符串中所有可能的单词排列

时间:2015-06-09 05:28:59

标签: perl permutation word

我有一个这样的字符串,how are you,我希望得到所有可能的字样,如

how are you
are how you
you how are
you are how
are you how
how you are

如何在perl脚本中创建它,我已经尝试了shuffle函数,但它只返回一串shuffle。
如果您不熟悉Perl脚本,则只能告诉我逻辑。

注意:字符串中的字数不是常数。

2 个答案:

答案 0 :(得分:5)

你所谈论的是permutations。这可以使用Algorithm::Permute模块在​​Perl中完成:

如果你已经安装了模块,这里有一个shell单行程,可以为你完成:

perl -e'
 use Algorithm::Permute qw();
 my $str = $ARGV[0]; 
 my @arr = split(/\s+/,$str);
 my $ap = new Algorithm::Permute(\@arr); 
 while (my @res = $ap->next()) { print("@res\n"); }
' 'how are you';
## you are how
## are you how
## are how you
## you how are
## how you are
## how are you

答案 1 :(得分:3)

您可以使用List::Permutor CPAN模块:

use strict;
use warnings;

use List::Permutor;

my $perm = new List::Permutor qw/ how are you /;
while (my @set = $perm->next)
{
  print "@set\n";
}

输出:

how are you
how you are
are how you
are you how
you how are
you are how

由于 bgoldst 建议Algorithm::Permute,为了更快地执行,您可以在不使用 while循环的情况下编写此代码:

use Algorithm::Permute;
my @array = qw(how are you);
Algorithm::Permute::permute {
    print "@array\n";
}@array;