使用perl构建数据库时循环回菜单?

时间:2013-03-22 00:13:43

标签: perl prompt

使用perl仍然在耳朵后面湿润,并尝试学习如何与MySQL一起使用它来完成数据库任务。我希望远离一个为用户提供菜单的perl脚本的开头,而不是要求输入,我已经开始使用数字1将用户输入加载到我之前指定的表中,我的问题是,当选择完成后,返回菜单打印语句的有效方法是什么?那么他们可以继续创建帐户等吗?

print "User Menu(please select 1-5):\n 1)Create a new account\n 2)List all the times       that an account has logged in\n 3)Log in/out of account\n 4)Drop and re-create the     necessary database tables\n 5)Quit\n";

$userInput = <>;

if($userInput == 1){
print "Please enter a user name: ";
$user_name = <>;
print "Please enter a password: ";
$password = <>;
$dbh->do("INSERT INTO user_accounts VALUES ('$user_name','$password')");
   #Trying to loop back to the menu.....
#}elsif($userInput == 2){
   #test:print "I am number 3";
#}elsif($userInput == 3){
   #test:print "I am number 3";
#}elsif($userInput == 4){
   #$dbh->do('DROP TABLE IF EXISTS user_accounts');
#test print "I am number 4";
}else{
exit;
}

1 个答案:

答案 0 :(得分:1)

我首先想到你想在后台执行任务,但如果你想要的只是返回菜单,那就把整个事情放在一个循环中。

另外,请查看numbered menus in IO::PrompterPrompt::ReadKey

use strict;
use warnings;

run();

sub run {
    my %dispatch = (
        1 => \&create_account,
        2 => \&list_log,
        3 => \&log_in_out,
        4 => \&recreate_tables,
        5 => \&quit,
    );

    while (1) {
        {
            local $| = 1;
            print menu(), '> ';
        }

        my $choice = <>;

        $choice =~ s/\A\s+//;
        $choice =~ s/\s+\z//;

        if (defined(my $handler = $dispatch{$choice})) {
            my $result = $handler->();
            unless (defined $result) {
                exit 0;
            }
        }
        else {
            warn "Invalid selection\n";
        }
    }
}

sub menu {
    return <<EO_MENU;
User Menu (please select 1-5):
1) Create a new account
2) List all the times that an account has logged in
3) Log in/out of account
4) Drop and re-create the necessary database tables
5) Quit
EO_MENU
}

sub create_account { print "create\n" }

sub list_log { print "list_log\n" }

sub log_in_out { print "log_in_out\n" }

sub recreate_tables { print "recreate_tables\n" }

sub quit { }