Hi supriyoch_2008,
I have gone through your script and there are several things to point out and correct, one of which is that you should always use strict in your scripts.
That been said I rewrote your whole script, but kept to the logic, you used, instead of pointing out errors and where to correct.
The code below is by no means perfect, but it fulfill OP initial desire I suppose.
use warnings;
use strict;
my $output = 'rData.txt';
while (1) {
my $entry = do {
print "\n\n Press 1 to insert new data:
\n Press 2 to view data:
\n Press 3 to call specific data:
\n Press 4 to Exit the Program: ";
<STDIN>;
};
chomp($entry);
my %menu = (
1 => \&menu_entry_1,
2 => \&menu_entry_2,
3 => \&menu_entry_3,
4 => sub { exit }
);
if ($entry) {
$menu{$entry}->(); # call the code_ref for each menu if true
}
}
sub read_file_DB {
my ( $file, $code_ref ) = @_;
open my $fh, '<', $file or die $!;
while (<$fh>) {
next if /^$/;
$code_ref->($_); # code ref
}
}
sub menu_entry_1 {
my $colon = ':';
my $dash = '~~~';
my $data;
print "\n\n Enter Student's Name: ";
chomp( my $std_name = <STDIN> );
$data .= $std_name . $colon;
print "\n Enter Age (yr): ";
chomp( my $std_age = <STDIN> );
$data .= $std_age . $colon;
print "\n Enter Regn Number: ";
chomp( my $std_rgn = <STDIN> );
$data .= $std_rgn . $dash . $/;
open my $fh, '>>', $output or die "cannot open file: $!";
print $fh $data, $/;
}
sub menu_entry_2 {
my $code = sub { print join "" => split /~~~/, shift };
read_file_DB( $output, $code );
}
sub menu_entry_3 {
my $sch_ref = {};
my $code = sub {
my $re = qr/:|~~~/;
my ( $name, $age, $reg_num ) = split /$re/, shift;
$sch_ref->{$reg_num}{$name} = $age;
};
read_file_DB( $output, $code );
print "Enter the Reg Number for Detailed information:";
chomp( my $std_reg_number = <STDIN> );
if ( $sch_ref->{$std_reg_number} ) {
print sprintf( "The Student name is %s and Age is %d\n",
%{ $sch_ref->{$std_reg_number} } );
}
else {
use Data::Dumper;
print Dumper $sch_ref;
}
}
Step through the codes above, you will understand it..
Hope it helps.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.