我是perl的新手,正在尝试使用简单开关的代码。学校服务器只运行Perl 5.12.4,所以我正在编码。
我遇到的问题是,控制开关的变量不会抛出任何情况,无论我如何描述它们,并且总是会陷入默认情况。
忽略每个案例开关的内容,我只是试图让它至少抛出print命令,所以我知道开关正在运行。
# 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";
}
}
}
答案 0 :(得分:4)
您必须在chomp($in);
之前添加switch
以删除换行符。
<>
读取流中的一行并包含换行符,其行为与类似scanf
的函数不同。
答案 1 :(得分:3)
你真的不想使用Switch
;这是一个非常古老的源过滤器模块,它不可靠,并且无论如何很久以前就从Perl中删除了。
对于更好的现代替代方案,请参阅Switch::Plain
或given/when
内置运算符,但请注意后者的“实验”警告行为。