我是 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/