Search code examples
perlvariablesglobal-variablessubroutine

perl call subroutine to generate random strings not working


The script to generate random strings:

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;

However, it works when it is not in a subroutine. And also works if the $string is a global variable. What did I miss? Thanks,


Solution

  • You need to explicitly add a return statement inside your subroutine. The automatic return of the last statement inside a subroutine does not work inside a loop construction, which in your example is a for loop. The postfix version of the for loop is equivalent to the regular version with curly braces.

    From 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.