Anonymous Monk:
Your first code snippet stores the result in $answer, but you haven't told it to print yet. Here's a quickie bit of code to show you a few variations on the theme:
use strict;
use warnings;
use v5.20;
my ($a_val, @some_vals);
# Store a scalar
$a_val = scalar_func(10);
# Print it later
say "A random number from 1 .. 10:";
say $a_val;
# Store a list
@some_vals = list_func(5, 10);
say "Print a list of values, each on one line";
say for @some_vals;
say "Print all the values on a single line";
say @some_vals;
say "Print all of them on a single line, with commas";
say join(", ", @some_vals);
# return a random integer from 1 to the specified number
sub scalar_func {
my $range = shift;
return 1 + int($range * rand);
}
# return $count random numbers from 1 .. $range
sub list_func {
my ($count, $range) = @_;
return map { scalar_func($range) } 1 .. $count;
}
Will print something like:
A random number from 1 .. 10:
1
Print a list of values, each on one line
3
1
10
10
3
Print all the values on a single line
3110103
Print all of them on a single line, with commas
3, 1, 10, 10, 3
Also, LanX is right: you don't want to use the 'for' clause when your function returns a single value. It doesn't do anything wrong in this case, but it's misleading: When reading the code, it implies that your function is returning a list of results.
...roboticus
When your only tool is a hammer, all problems look like your thumb. |