JLo*_*ott 1 terminal perl file-io compiler-errors padre
我正在编写一个简单的程序,从文件中读取莫尔斯代码并将其转换为纯文本.我虽然得到了一些疯狂的错误.我对perl不太熟悉,我不得不从命令行运行它.以下是我收到的错误和代码.我可能错误地运行了它.我在命令行输入:"perl -w Lott_Morse.pl morse.txt".任何帮助,将不胜感激.
错误:
Use of uninitialized value in print at Lott_CSC360_Morse2.pl line 31, <> line 7.
Use of uninitialized value in print at Lott_CSC360_Morse2.pl line 31, <> line 7.
Use of uninitialized value in print at Lott_CSC360_Morse2.pl line 31, <> line 7.
Use of uninitialized value in print at Lott_CSC360_Morse2.pl line 31, <> line 7.
Use of uninitialized value in print at Lott_CSC360_Morse2.pl line 31, <> line 7.
Use of uninitialized value in print at Lott_CSC360_Morse2.pl line 31, <> line 7.
The message is 0Jessicas-MacBook-Pro:Documents
Run Code Online (Sandbox Code Playgroud)
码:
#!/usr/bin/perl
use 5.010;
use warnings;
%morse_to_plain=(
".-" =>"A", "-..." => "B", "-.-." => "C", "-.." => "D", "." => "E",
"..-." => "F", "--." => "G", "...." => "H", ".." => "I", ".---" => "J",
"-.-" => "K", ".-.." => "L", "--" => "M", "-." => "N", "---" => "O",
".--." => "P", "--.-" => "Q", ".-." => "R", "..." => "S", "-" => "T",
"..-" => "U", "...-" => "V", ".--" => "W", "-..-" => "X", "-.--" => "Y",
"--.." => "Z", "-----" => "0", ".----" => "1", "..---" => "2", "...--" => "3",
"....-" => "4", "....." => "5", "-...." => "6", "--..." => "7", "---.." => "8",
"----." => "9", ".-.-.-" => ".", "--..--" => ",", "..--.." => "?", ".----." => "'",
"-....-" => "-", ".-..-." => '"', ".--.-." => "@", "-...-" => "=", "!" => " "
);
chomp(@message = <>);
print "The message is ";
foreach $char (@message)
{
print $morse_to_plain{$char};
}
Run Code Online (Sandbox Code Playgroud)
您正在读取散列中没有匹配键的字符串,因此散列值未定义(未初始化).这可能是输入问题.试试这个用于调试目的:
print $morse_to_plain{$char} // "Key does not exist: '$char'\n";
Run Code Online (Sandbox Code Playgroud)
对于更长的字符串,您可以考虑这样:
$string =~ s{([-.]+)}{ $morse_to_plain{$1} // $1 }ge;
Run Code Online (Sandbox Code Playgroud)
这将搜索点和短划线的组合并将它们转换为等效的文本,或者如果没有找到翻译则将它们自己翻译.
您还应该考虑使您的哈希赋值更具可读性:
my %morse_to_plain = (
".-" => "A", "-..." => "B", "-.-." => "C", "-.." => "D", "." => "E",
"..-." => "F", "--." => "G", "...." => "H", ".." => "I", ".---" => "J",
"-.-" => "K", ".-.." => "L", "--" => "M", "-." => "N", "---" => "O",
".--." => "P", "--.-" => "Q", ".-." => "R", "..." => "S", "-" => "T",
"..-" => "U", "...-" => "V", ".--" => "W", "-..-" => "X", "-.--" => "Y",
"--.." => "Z", "-----" => "0", ".----" => "1", "..---" => "2", "...--" => "3",
"....-" => "4", "....." => "5", "-...." => "6", "--..." => "7", "---.." => "8",
"----." => "9", ".-.-.-" => ".", "--..--" => ",", "..--.." => "?", ".----." => "'",
"-....-" => "-", ".-..-." => '"', ".--.-." => "@", "-...-" => "=", "!" => " "
);
Run Code Online (Sandbox Code Playgroud)
它会使拼写错误更容易被发现.此外,您可以轻松地创建反向查找表:
my %plain_to_morse = reverse %morse_to_plain;
Run Code Online (Sandbox Code Playgroud)