gpt4 book ai didi

perl - 编译错误: Requires Explicit Package Name

转载 作者:行者123 更新时间:2023-12-02 10:44:43 25 4
gpt4 key购买 nike

我只是从Perl开始,我正在编写一个程序,该程序读取一个文件,并将该文件中的莫尔斯电码放入另一个文件中的纯文本中。我收到此错误,我无法弄清楚出什么问题了。任何帮助表示赞赏!

我收到错误:

Jessicas-MacBook-Pro:Documents jessica$ perl -w Morse_to_Text.pl <Morse3.rtf> MorseTest.txt
Global symbol "$message" requires explicit package name at Morse_to_Text.pl line 20.
Global symbol "$message" requires explicit package name at Morse_to_Text.pl line 26.
Global symbol "$message" requires explicit package name at Morse_to_Text.pl line 26.
Global symbol "$message" requires explicit package name at Morse_to_Text.pl line 27.

码:
#!/usr/bin/perl 

use 5.010;
use strict;
use warnings;


my %morsecode=(
".-" =>"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", ".-.-.-" => ".", "--..--" => ",", "..--.." => "?", ".----." => "'",
"-....-" => "-", ".-..-." => '"', ".--.-." => "@", "-...-" => "=", "!" => " "
);


while (<>) {
chomp;
foreach my $char ( split ' ' ) {

$message = $morsecode{$char} + $message;
print $message;
};
}

最佳答案

您使用strict,因此应首先声明全局变量$ message。但是正如ikegami在评论中所说,使用严格和警告是编写perl代码时的最佳实践之一。编译指示会尽快捕获许多错误,否则它们就会被捕获,这使得更容易找到错误的根本原因(就像您提供的错误一样)。根本原因可能是需要进行错误或验证检查,而无论程序员是否熟练,这都可能发生。

我认为您想要的是以下代码:

#!/usr/bin/perl 

use 5.010;
use strict;
use warnings;


my %morsecode=(
".-" =>"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", ".-.-.-" => ".", "--..--" => ",", "..--.." => "?", ".----." => "'",
"-....-" => "-", ".-..-." => '"', ".--.-." => "@", "-...-" => "=", "!" => " "
);

my $message;

while (<>) {
chomp;
foreach my $char ( split ' ' ) {
$message = $message.$morsecode{$char};
};
}

print $message."\n";

关于perl - 编译错误: Requires Explicit Package Name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14741640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com