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

Hello stevek1974 and welcome to the monastery and the wonderful world of Perl,

I present a little, and ugly, program that do what you described. You mention that you want the resulting index starting at 1. You know is easier following the array rule, i.e. start with 0. More: i presented a solution using array as you asked even if i prefere using hashes because their keys are unique and the code below admit duplicate entries (input: 1,1,1,1 lead to unwanted results IMHO)
#!/usr/bin/perl use strict; use warnings;<P> my @names = qw (Tizio Caio Sempronio);<P> show_indexed();<P> my @selected = select_by_index(); print "First choice:\n--->",(join "\n--->",@selected),"\n";<P> ## and then.. push @names,'stevek1974'; show_indexed();<P> my @selected_bis = select_by_index(); print "Second choice:\n--->",(join "\n--->",@selected_bis),"\n";<P> ###################################################################### +########## sub show_indexed { print "\nChoice one or more name, using their index:\n"; my $index = 0; foreach my $name (@names){ print "[$index]\t$name\n"; $index++; } print "\n"; } ###################################################################### +########## sub select_by_index { my $in = <STDIN>; chomp $in; # checks are needed in thi case.. unless ($in=~/^[\d,]+$/){warn "WARNING: invalid input!\n";select_b +y_index()}<P> my @choice = @names[split /,/, $in];#thanks to tye and choroba: i +used @names[eval $in] # more checks are better.. unless (defined $choice[0]){ warn "WARNING: probably you need to check that input numbe +rs are valid for the current array!\n"; select_by_index() } return @choice; }
Update: the above script is too simple and bugged too: after an invalid input is no more possible to give a valid one!

HtH
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
  • Comment on Re: Adding a numeric key to list items and creating a user selection list (little example)
  • Download Code

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

    I am actually working with the snippet provided by hippo. It is working for the most part and I've modified it a bit to get to my end goal. I just need to fix formatting a bit and add the error checking, but so far so good.

    Thanks for your suggestion as well.