in reply to How to search a Name from a file and extracts its designation
and your code asSLNO FirstName LastName Desgination ----------------------------------------------------- 1 Pragya Singh Developer 2 George Shepered SME 3 Akshay Bhargav SME 4 Amey Deshmukh Developer 5 Bhushan Bhatkar Quality 6 Dinesh Yadav Support ------------------------------------------------------
It's considered good practice for a number of reasons to use strict, indirect file handles, and three-argument open. Fixing that plus some extraneous minor issues would transform your code to:#!/perl/bin/perl $fname = "Designations.txt"; open (WXYZ, $fname) or die "Couldn't open file Designations.txt, $!"; while (<WXYZ>) { print "$_"; } print "Enter First Name or Last Name: \n \n"; $name = <STDIN>; print "Entered name is : $name \n";
In order to do the mapping you suggest, you should probably build a hash in conjunction with split in your while loop. The fact that you've presupposed using "if statements and match operators" makes me think this is a homework assignment, in which case you should tell us as much. My solution might look like:#!/perl/bin/perl use strict; use warnings; my $fname = 'Designations.txt'; open (my $fh, '<', $fname) or die "Couldn't open file $fname, $!"; while (<$fh>) { print; } print "Enter First Name or Last Name: \n \n"; my $name = <STDIN>; print "Entered name is : $name \n";
Of course, this could fail for a number of potential reasons, but identifying those are a exercise for the user.#!/perl/bin/perl use strict; use warnings; my $fname = "Designations.txt"; open (my $fh, '<', $fname) or die "Couldn't open file $fname, $!"; my %designation; while (<$fh>) { my ($SLNO, $first, $last, $desig) = split /\s+/; $designation{$first} = $desig; $designation{$last} = $desig; } print "Enter First Name or Last Name: \n \n"; chomp(my $name = <STDIN>); print "Entered name is : $name \n"; print "Designation is : $designation{$name}\n";
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to search a Name from a file and extracts its designation
by amey (Initiate) on Jan 25, 2015 at 15:07 UTC |