7.7. Array index (menu)

  • $#array - the largest index

  • $array[1] - array elements are scalar

Example 7-3. examples/arrays/color_menu.pl

#!/usr/bin/perl
use strict;
use warnings;

my $color;

my @colors = ("Blue", "Yellow", "Brown", "White");
print "Please select a number:\n";
foreach my $i (0..$#colors) {
    print "$i) $colors[$i]\n";
}
my $num = <STDIN>;
chomp($num);
if (defined $colors[$num]) {
    $color = $colors[$num];
} else {
    print "Bad selection\n";
    exit;
}

print "The selected color is $color\n";

If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed