Perl 5.12.4,开关不工作?

标签 perl switch-statement

我是 perl 的新手,正在尝试使用简单开关的代码。学校服务器仅运行 Perl 5.12.4,因此我正在相应地进行编码。

我遇到的问题是控制开关的变量不会抛出任何情况,无论我如何描述它们,并且总是落入默认情况。

忽略每个 case 开关的内容,我只是想让它至少抛出打印命令,这样我就知道开关正在运行。

# I have tried: case "1", case 1, case [1], case '1', and other variations.

#!/usr/bin/perl
# script name: phonebook.pl
while ( 1 ) {
print "Welcome to the Registry Searcher!\n";
print "Please enter a command matching one of the options below.\n";
print "1) List records alphabetically\n";
print "2) List records reverse alphabetically\n";
print "3) Search the Registry by Name\n";
print "4) Search the Registry by Birthday\n";
print "5) Exit\n";
print "Choice: ";
$in = <>;
    # user enters "1".
use Switch;
switch ($in) {
    case 1 {
        print "Please choose either first or last name (f/l): ";
        $type = <>;
        if ( $type == f ) {
            sort list.txt;
        } elsif ( $type == "l" ) {
            sort -k2 list.txt;
        } else {
            print "Choice not recognized.\n";
        }
        print "Please press enter to continue...";
        $cont = <>;
    }
    case 2 {
        print "Please choose either first or last name (f/l): ";
        $type = <>;
        if ( $type == "f" ) {
            sort -r list.txt
        } elsif ( $type == "l" ) {
            sort -rk2 list.txt
        } else {
            print "Choice not recognized.\n";
        }
        print "Please press enter to continue...";
        $cont = <>;
    }
    case 3 {
        print "Please enter a last name to search for: ";
        $name = <>;
        # awk '/^[A-Z][a-z]+ '$name'/{print}' list.txt;
        print "Please press enter to continue...";
        $cont = <>;
    }
    else {
    print "not found\n";
    }
}
}

最佳答案

您必须添加 chomp($in);switch 之前删除换行符。

<>读取流中的一行并包含换行符,行为不同于 scanf -样的功能。

关于Perl 5.12.4,开关不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339993/

相关文章:

perl - 如何获取其键与给定正则表达式匹配的哈希元素?

perl - 在 Perl 中识别日期字符串

macos - git-svn 全新安装 macOS Catalina 10.15.4 后找不到 SVN/Core.pm

perl - 如何检查对象是否具有特定方法?

c - 为什么 `switch` 这么慢?

mysql - 试图找出为什么 sub 会导致 mysql 数据库中有 27 个条目

c# - 如何在 C# 中使用字节常量作为 switch case?

c# - 在 C# 中使用 enum 和 struct 代替 switch 语句

PHP 在 while 循环中切换

r - 开关/外壳的成语