說所有的可能的組合我有一個哈希:與關鍵
1 => 1
2 => abc
3 => xyz
在Perl中,我怎麼可以給像211的字符串,並得到所有可能的組合,根據該散列:abc11,1abc1,11abc等...
說所有的可能的組合我有一個哈希:與關鍵
1 => 1
2 => abc
3 => xyz
在Perl中,我怎麼可以給像211的字符串,並得到所有可能的組合,根據該散列:abc11,1abc1,11abc等...
上面有鏈接上CPAN幾個列表排列模塊,許多問題: How can I generate all permutations of an array in Perl?
使用List::Permutor模塊:
my $template = 211;
my %strings = (
1 => 1,
2 => 'abc',
3 => 'xyz',
);
use List::Permutor();
my $perm = List::Permutor->new(split //, $template);
my %seen;
while (my @set = $perm->next) {
my $str = join '' => @strings{@set};
say $str unless $seen{$str}++;
}
它打印:
abc11 1abc1 11abc
請注意,您必須使用裸數字問題,您的模板,如果你超越鍵0 .. 9
。 (是否10
的意思是10
或1,0
...)。你應該改變你的模板來創建一個記錄分隔符。
你可以嘗試像,從字符串得到的數字和循環並構建字符串:
my @digits = ($str =~ /(\d)/g);
my $val;
foreach (@digits) {
# %values holds key/value pairs
$val .= $values{$_};
}
這是一個散列,而不是一個列表。 – 2012-01-30 21:39:55
可能的重複:http://stackoverflow.com/questions/635768/how-can-i-generate-all-permutations-of-an-array-in-perl – Richard 2012-01-30 21:45:38