in reply to pattern string match while reading from the file

Another approach: File select_1.pl:

use warnings; use strict; use Data::Dump; # for development/debug # you will have to open and process some kind of config file, # but i will use __DATA__ my %services; while (my $record = <DATA>) { my ($n, $service) = $record =~ m{ \A (\d+) \s* : \s* (.*?) \s* \z }xms; if (! defined($n) or ! defined($service)) { die "bad config file record '$record'" } if (exists $services{$n}) { die "duplicated service number $n: '$service'"; } $services{$n} = $service; } # dd \%services; # FOR DEBUG print "$_: $services{$_} \n" for sort { $a <=> $b } keys %services; my $n; CHOICE: { print "Please choose a number from the list above: "; chomp($n = <STDIN>); last CHOICE if exists $services{$n}; print "'$n' is not on the list. Please choose again. \n"; redo CHOICE; } print "You chose $n: '$services{$n}' \n"; __DATA__ 1: Recturing Svc 2: Finance 9: Payments 19: Mobile 29: Bankers
Output:
c:\@Work\Perl\monks\perlDevsWorld>perl select_1.pl 1: Recturing Svc 2: Finance 9: Payments 19: Mobile 29: Bankers Please choose a number from the list above: 3 '3' is not on the list. Please choose again. Please choose a number from the list above: xx 'xx' is not on the list. Please choose again. Please choose a number from the list above: 9 You chose 9: 'Payments'


Give a man a fish:  <%-(-(-(-<

Replies are listed 'Best First'.
Re^2: pattern string match while reading from the file
by Laurent_R (Canon) on Apr 10, 2015 at 17:50 UTC
    I think that this approach is much better than anything before (and I would have suggested something along the same line if you had not done it).

    Storing the data in a hash (or possibly an array) makes it possible to have instant in-memory access to the data, instead of having to read through the file each time over.

    Je suis Charlie.