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

get all possible permutations of words in string using perl script

我有一个像这样的字符串,how are you,我想得到所有可能的单词随机排列,比如

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

如何在 perl 脚本中实现,我试过 shuffle 函数,但它 returns 只有一串随机播放。
如果你不熟悉Perl脚本,你可以只告诉我逻辑。

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

你说的是permutations. This can be done in Perl with the Algorithm::Permute模块:

如果您已经安装了该模块,这里有一个 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

您可以使用 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;