in reply to Adding a numeric key to list items and creating a user selection list

Use a counter:

my @vdbhosts = sort @lines; my $count = 1; for ( @vdbhosts ) { print "$count: $vdbhosts[ $count ]\n"; $count++; }
Also, don't use File::Slurp -- it's broken. Use File::Slurper or Path::Tiny instead.

Hope this helps!

The way forward always starts with a minimal test.
  • Comment on Re: Adding a numeric key to list items and creating a user selection list
  • Download Code

Replies are listed 'Best First'.
Re^2: Adding a numeric key to list items and creating a user selection list
by stevek1974 (Novice) on Sep 25, 2015 at 18:38 UTC

    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

      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.

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