- 论坛徽章:
- 0
|
本帖最后由 伍式南 于 2015-09-27 15:17 编辑
有两个几乎一样的程序,只在第9,10行处有区别:一个声明变量时用了my,一个没用.结果是,一个可以正常运行,一个不能
可以正常运行的代码:- while (<DATA>) {
- chomp;
- my ($head, $all) = /^(.) (.*)$/;
-
- $pytable{$head} = $all;
- }
- sub getheadstr {
- @str = split '', $_[0];
- @res = ();
-
- sub loop {
- my ($no, $head) = @_;
-
- for (split ' ', $pytable{$str[$no]}) {
- if ($no == $#str) {
- push @res, $head . $_;
- } else {
- loop($no + 1, $head . $_);
- }
- }
- }
-
- loop(0, "");
-
- undef %count;
- return join ' ', grep { ++$count{ $_ } < 2; } @res;
- }
- print getheadstr("ab") . "\n";
- print getheadstr("ab") . "\n";
- __DATA__
- a alpha ALPHA
- b beta BETA
复制代码 有问题的代码:- while (<DATA>) {
- chomp;
- my ($head, $all) = /^(.) (.*)$/;
-
- $pytable{$head} = $all;
- }
- sub getheadstr {
- my @str = split '', $_[0];
- my @res = ();
-
- sub loop {
- my ($no, $head) = @_;
-
- for (split ' ', $pytable{$str[$no]}) {
- if ($no == $#str) {
- push @res, $head . $_;
- } else {
- loop($no + 1, $head . $_);
- }
- }
- }
-
- loop(0, "");
-
- undef %count;
- return join ' ', grep { ++$count{ $_ } < 2; } @res;
- }
- print getheadstr("ab") . "\n";
- print getheadstr("ab") . "\n";
- __DATA__
- a alpha ALPHA
- b beta BETA
复制代码 它们的输出:- timmy@wh1te:~/jianweizhizhuo$ perl good.pl
- alphabeta alphaBETA ALPHAbeta ALPHABETA
- alphabeta alphaBETA ALPHAbeta ALPHABETA
- timmy@wh1te:~/jianweizhizhuo$ perl bad.pl
- alphabeta alphaBETA ALPHAbeta ALPHABETA
- timmy@wh1te:~/jianweizhizhuo$ diff good.pl bad.pl
- 9,10c9,10
- < @str = split '', $_[0];
- < @res = ();
- ---
- > my @str = split '', $_[0];
- > my @res = ();
复制代码 "有问题的代码"中的getheadstr函数只能被调用一次,如果我再调用一次,它就会返回一个空值
我想知道,为什么会这样? |
|