利用perl中的菜单,在命令后循环回主菜单

时间:2014-09-24 00:24:49

标签: perl menu cycle

我想在命令或菜单命令完成后循环回到主菜单,在我的代码中给出了一些东西,菜单选项1会循环,但是一旦我得到正确列出文件和文件夹的命令,停止。

#!/usr/bin/perl -w

use strict;

my $menu1;
my $menu2;
my $menu3;
my $directory = '/home/jkiger';

my $quit_menu_item = [ "Quit", sub { exit; } ];

$menu1 = [
    "Chose a command for the home folder: ",
    [ "list home directory files and folders", \&ds1 ],
    [ "List file types in home directory",     \&ds2 ],
    [ "List file types in home directory",     \&ds3 ],
    [ "Quit", sub { exit; } ],
];

sub menu {
    my $m = shift;
    my $choice;
    while (1) {
        print "$m->[0]:\n";
        print map {"\t$_. $m->[$_][0]\n"} ( 1 .. $#$m );
        print "> ";
        chomp( $choice = <> );
        last if ( ( $choice > 0 ) && ( $choice <= $#$m ) );
        print "You chose '$choice'.  That is not a valid option.\n\n";
    }
    &{ $m->[$choice][1] };
}

sub ds1 {
    system("ls $directory") or die $!;
    &menu($menu1);
}

sub ds2 {
    system("ls -p $directory") or die $!;
    &menu($menu2);
}

sub ds3 {
    system("ls -s $directory") or die $!;
    &menu($menu3);
}

&menu($menu1);
&menu($menu2);
&menu($menu3);

1 个答案:

答案 0 :(得分:1)

当您找到有效选项时,不要打破循环,只需执行代码并继续:

chomp( my $choice = <> );

if ( $choice > 0 && $choice <= $#$m ) {
    $m->[$choice][1]();
} else {
    print "You chose '$choice'.  That is not a valid option.\n\n";
}

对于其他一些提示,我会指出以下内容

  1. 对分派表而不是数组使用%哈希。这有助于您在验证使用有效值之前避免检查数据类型。
  2. 阅读system的规范,了解如何正确检查错误。
  3. 以下是完成相同任务的脚本简化:

    #!/usr/bin/perl -w
    use strict;
    use warnings;
    
    my $directory = '/home/jkiger';
    
    my %dispatch = (
        1 => sub { system( 'ls', $directory ) == 0 or die $? },
        2 => sub { system( 'ls', '-p', $directory ) == 0 or die $? },
        3 => sub { system( 'ls', '-s', $directory ) == 0 or die $? },
        4 => sub {exit},
    );
    
    while (1) {
        print <<"END_PROMPT";
    Chose a command for the home folder: 
    1. List home directory files and folders
    2. List file types in home directory
    3. List file types in home directory
    4. Quit
    END_PROMPT
    
        chomp( my $choice = <> );
    
        if ( $dispatch{$choice} ) {
            $dispatch{$choice}();
        } else {
            print "You chose '$choice'.  That is not a valid option.\n\n";
        }
    }