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.
Step through the codes above, you will understand it..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; } }
In reply to Re: How can one initialize the scalar $reg_no in hash element?
by Anonymous Monk
in thread How can one initialize the scalar $reg_no in hash element?
by supriyoch_2008
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |