在听说 Perl 一年之后,我决定抽出几个小时的时间来看看我能学到多少。我很好地完成了基础知识,然后进入了循环。作为一个测试,我想看看我是否可以构建一个脚本来递归所有最多 4 个字符的字母数字值。前段时间我写了一个 PHP 代码做同样的事情,所以我采用了相同的概念并使用它。但是,当我运行脚本时,它会将“a”作为前 3 个值,然后仅循环遍历最后一个数字。有人看到我做错了吗?
#!/usr/local/bin/perl
$chars = "abcdefghijklmnopqrstuvwxyz";
$chars .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$chars .= "0123456789";
@charset = split(//, $chars);
$charset_length = scalar(@charset);
sub recurse
{
($width, $position, $base_string) = @_;
for ($i = 0; $i < $charset_length; ++$i) {
$base = $base_string . $charset[$i];
if ($position < $width - 1) {
$pos = $position + 1;
recurse($width, $pos, $base);
}
print $base;
print "\n";
}
}
recurse(4, 0, '');
这是我运行它时得到的:
aaaa
aaab
aaac
aaad
aaae
aaaf
aaag
aaah
aaai
aaaj
aaak
aaal
aaam
aaan
aaao
aaap
aaaq
aaar
aaas
aaat
aaau
aaav
aaaw
aaax
aaay
aaaz
aaaA
aaaB
aaaC
aaaD
aaaE
aaaF
aaaG
aaaH
aaaI
aaaJ
aaaK
aaaL
aaaM
aaaN
aaaO
aaaP
aaaQ
aaaR
aaaS
aaaT
aaaU
aaaV
aaaW
aaaX
aaaY
aaaZ
aaa0
aaa1
aaa2
aaa3
aaa4
aaa5
aaa6
aaa7
aaa8
aaa9
aaa9
aaa9
aaa9