in reply to Re^2: Adding a numeric key to list items and creating a user selection list
in thread Adding a numeric key to list items and creating a user selection list
Add an unused entry to the front of the array,
then indexes will align with the data in the way you want.
Here's a partial example:
#!/usr/bin/perl # http://perlmonks.org/?node_id=1143022 use strict; use warnings; my @names = qw( aaa bbbb ccccc dddd ee fffff gggg hhhhhh ); # add unused item to front to align names with indexes unshift @names, 'unused'; for my $index (1 .. $#names) { printf "%2d %s\n", $index, $names[$index]; } print "\nselect desired by number:\n"; my $in = <STDIN>; # validate input chomp $in; $in =~ /^[\d,\s]+$/ or die "$in is an invalid input"; for my $index ($in =~ /\d+/g ) { if( $index >= 1 and $index <= $#names ) { print "selected $names[$index]\n"; } else { die "$index is outside the allowable range\n"; } }
This is perl. Why try to cope with "off by one" (add 1 or subtract 1?) if you don't have to? :)
|
|---|