Pattern matching while reading from the files using Perl -


i'm running issue while reading file , matching pattern

file content

1: recturing svc 2: finance     :     : 9: payments     :     : 19: mobile      :      : 29: bankers 

my code looks this

open(inputfile, "<$conf_file") or die("unable open text file"); foreach (<inputfile>) {   print "$_"; } close inputfile;  print "please choose number list above: "; chop($input = <stdin>); $input = trim($input); print "your choice was: $input\n";  $temp = "$input:"; open(inputfile, "<$conf_file") or die("unable open text file comparision"); foreach $line (<inputfile>) {   if ($line =~ /$temp/) {     print " exact match: $& \n";     print " after match: $' \n";     $svc = $';     print "servicel $svc \n";   } } close inputfile; 

it matching multiple items, example 9: , 19: , 29: when select. example, if enter 9 prints

 9: payments 19: mobile 29: bankers 

i suggest read options file array doesn't need opened , read twice

something perhaps? regular expression in if $input =~ /(\d+)/ extracts number input there no need remove spaces or newline, while and $menu[$1] checks such number exists in menu

use strict;  use warnings;   $conf_file = 'conf_file.txt';  @menu; {   open $fh, '<', $conf_file or die qq{unable open "$conf_file" input: $!};   while ( <$fh> ) {     if ( /(\d+)\s*:\s*(.*\s)/ ) {       $menu[$1] = $2;       print;     }   } }  $option; until ( $option) {   print "please choose number list above: ";   $input = <stdin>;   $option = $1 if $input =~ /(\d+)/ , $menu[$1]; }  print "your choice was: $option\n"; print "corresponding $menu[$option]\n"; 

output

e:\perl\source>conf_file.pl 1: recturing svc 2: finance 9: payments 19: mobile 29: bankers please choose number list above: 3 please choose number list above: 9 choice was: 9 corresponding payments 

Popular posts from this blog