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

del*_*air 1 variables perl global-variables subroutine

用于生成随机字符串的脚本:

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;
Run Code Online (Sandbox Code Playgroud)

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

xxf*_*xxx 11

您需要return在子例程中显式添加语句.在子例程中自动返回最后一个语句在循环结构中不起作用,在您的示例中,循环结构是for循环.for循环的后缀版本等同于带花括号的常规版本.

来自perldoc perlsub:

如果未找到"return"且如果最后一个语句是表达式,则返回其值.如果最后一个语句是循环控制结构,如"foreach"或"while",则返回的值未指定.空子返回空列表.