in reply to Re: 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

This sort of worked. When I use this code as specified, I get results numbered 1 - 7. The problem is there are 8 records in the file. It skips the first item in the array with the index of 0. If I change it to count = 0, I get all 8 items but numbered starting at 0

  • Comment on Re^2: Adding a numeric key to list items and creating a user selection list

Replies are listed 'Best First'.
Re^3: Adding a numeric key to list items and creating a user selection list
by 1nickt (Canon) on Sep 25, 2015 at 20:40 UTC

    Cool! Besides the solution you were shown involving adding one to the index before you print it, you could also use unshift to pad the array and work with its true index:

    my @vdbhosts = sort @lines; unshift @vdbhosts, 'padding'; my $count = 0; for ( @vdbhosts ) { my $host = $vdbhosts[ $count ]; print "$count: $host\n" unless $host eq 'padding'; $count++; }
    Hope this helps!

    Edit: added alternative solution example, my original reply didn't add much ;-)

    The way forward always starts with a minimal test.

      Getting there. Actually working of the suggestion provided by hippo. Making progress. Thanks for your suggestion as well.

Re^3: Adding a numeric key to list items and creating a user selection list
by Anonymous Monk on Sep 25, 2015 at 22:55 UTC

    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? :)