in reply to Error while taking 'Scalar of scalar'

my @color= qw( lavender lightblue honeydew); my $color_no=int(rand($#color)); return $color[$color_no];
have you ever wondered why you only get back the first two colors? rand(x) returns a random number between 0 and (excluding) x.

the usual idiom for this in perl is:

my @colors = qw(lavender lightblue honeydew); my $color = $colors[rand @colors]; return $color;

Replies are listed 'Best First'.
Re^2: Error while taking 'Scalar of scalar'
by bart (Canon) on Jul 05, 2007 at 12:39 UTC
    my $color = $colors[rand @colors];
    Or
    my $color = $colors[int rand @colors];
    which does the exact same thing, but doesn't depend on the knowledge that numbers used as array indexes are truncated to integer, instead of rounded.