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 ...";
- $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
- while(1) {
- #inner loop until user enters correct option
- while(1) {
- # print menu & prompt/chomp for user input: $choice
- print "Choose 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: ";
- my $choice = <>;
- chomp($choice);
- # if user enters '5' then quit by exiting outer loop
- if ($choice eq '5') {last outer_loop;}
- # if the user enters a valid choice, exit inner loop
- if (exists($function{$choice})) {last inner_loop;}
- 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
- } # 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"";
- 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
Add Comment
Please, Sign In to add comment