perl调用子程序生成随机字符串不起作用

perl call subroutine to generate random strings not working

生成随机字符串的脚本:

sub rand_Strings {
   my @chars = ("A".."Z", "a".."z", "0".."9");
   my $string;
   $string .= $chars[rand @chars] for 1..8;
}

my $strings = &rand_Strings;
print $strings;

但是,当它不在子程序中时,它可以工作。如果 $string 是全局变量,也可以使用。我错过了什么?谢谢,

您需要在子例程中显式添加 return 语句。 子例程中最后一条语句的自动 return 在循环构造中不起作用,在您的示例中是 for 循环。 for 循环的后缀版本相当于带花括号的常规版本。

来自perldoc perlsub

If no "return" is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a "foreach" or a "while", the returned value is unspecified. The empty sub returns the empty list.