Guest User

Untitled

a guest
Sep 27th, 2017
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. use strict;
  2. use lib './';
  3. use functs_skeleton;
  4.  
  5.  
  6. # create a hash of functions--see asmt sheet
  7. my %function = { '1' => \&add_user, '2' => \&edit_user, '3' => \&delete_user, '4' => \&print_list};
  8. #global var declarations go here
  9. my $fh;
  10. my $fn;
  11. my %hash;
  12. #Open file for reading
  13. # prompt user for filename & store in variable:"$fn" : print, <>, chomp
  14. print "Enter ...";
  15. $fn = <>;
  16. chomp($fn);
  17.  
  18. open ($fh, "<", $fn);
  19. # if file does not exist, create it by opening an empty file for writing
  20. if (!$fh) {
  21. open ($fh, ">", $fn);
  22. }
  23. #transfer file line by line into hash with a while loop, splitting the username and password by the delimiter character ":"
  24. while (my $line = <$fh>) {
  25. my @line_array = split(/:/,$line);
  26. my $username = $line_array[0];
  27. my $password = $line_array[1];
  28. chomp($password);
  29. $hash{$username} = $password;
  30. }
  31. # outer loop until user quits
  32. while(1) {
  33. #inner loop until user enters correct option
  34. while(1) {
  35. # print menu & prompt/chomp for user input: $choice
  36. 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: ";
  37. my $choice = <>;
  38. chomp($choice);
  39. # if user enters '5' then quit by exiting outer loop
  40. if ($choice eq '5') {last outer_loop;}
  41. # if the user enters a valid choice, exit inner loop
  42. if (exists($function{$choice})) {last inner_loop;}
  43. print "Unknown choice\n";
  44. } #end of the inner loop
  45. # set local variable to appropriate function references in hash by user's choice & call appropriate function by passing in the hash as a parameter
  46. # and assigning the function result to the hash to update it
  47.  
  48. } # end of outer loop
  49.  
  50. #Close the file for reading
  51. close($fh);
  52. # prompt user to save changes, if so, then print the entire contents of the hash to the file & close the file for writing
  53. print"";
  54. my $saveit = <>;
  55. chomp($saveit);
  56. if ($saveit eq 'y') {
  57. open( $fh, ">", $fn);
  58. #for every entry in the hash, write it to the file
  59. foreach my $key (keys %hash) {
  60. print $fh $key . ":" . $hash{$key} . "\n";
  61. }
  62. close($fh);
  63. } # if
Add Comment
Please, Sign In to add comment