Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use strict;
- use lib './';
- use functs_skeleton;
- # create a hash of functions--see asmt sheet
- my %function = ( '1' => \&add_user, '2' => \&edit_user, '3' => \&delete_user, '4' => \&print_list);
- #global var declarations go here
- my $fh;
- my $fn;
- my %hash;
- #Open file for reading
- # prompt user for filename & store in variable:"$fn" : print, <>, chomp
- print "Enter Filename: ";
- $fn = <>;
- chomp($fn);
- open ($fh, "<", $fn);
- # if file does not exist, create it by opening an empty file for writing
- if (!$fh) {
- open ($fh, ">", $fn);
- }
- #transfer file line by line into hash with a while loop, splitting the username and password by the delimiter character ":"
- while (my $line = <$fh>) {
- my @line_array = split(/:/,$line);
- my $username = $line_array[0];
- my $password = $line_array[1];
- chomp($password);
- $hash{$username} = $password;
- }
- # outer loop until user quits
- outer:{
- while(1) {
- #inner loop until user enters correct option
- my $func = "UNSET";
- my $choice;
- inner:{
- while(1) {
- # print menu & prompt/chomp for user input: $choice
- print "\n\nChoose an option:\n\t1. Add user account\n\t2. Edit existing user account\n\t3. Delete existing user account\n\t4. Print list of user accounts\n\t5. Save and quit\n\nEnter choice: ";
- $choice = <>;
- chomp($choice);
- if ($choice eq '5') {last outer;}
- # if the user enters a valid choice, exit inner loop
- # if ($choice eq '1') {$func=\&add_user;last;}
- # if ($choice eq '2') {$func=\&edit_user;last;}
- # if ($choice eq '3') {$func=\&delete_user;last;}
- # if ($choice eq '4') {$func=\&print_list;last;}
- #print"choice='".$choice."', val='".$function{$choice}."'\n";
- if (exists($function{$choice})) {last;}
- print "Unknown choice\n";
- } #end of the inner loop
- }
- # set local variable to appropriate function references in hash by user's choice & call appropriate function by passing in the hash as a parameter
- # and assigning the function result to the hash to update it
- # print"choice=".$choice."\n";
- %hash = $function{$choice}->(\%hash);
- } # end of outer loop
- }
- #Close the file for reading
- close($fh);
- # prompt user to save changes, if so, then print the entire contents of the hash to the file & close the file for writing
- print "Save (y/n)?";
- my $saveit = <>;
- chomp($saveit);
- if ($saveit eq 'y') {
- open( $fh, ">", $fn);
- #for every entry in the hash, write it to the file
- foreach my $key (keys %hash) {
- print $fh $key . ":" . $hash{$key} . "\n";
- }
- close($fh);
- } # if
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement