perl脚本返回错误全局符号需要显式包

时间:2014-10-31 09:33:15

标签: perl

我正在尝试编写一个perl脚本,其中有一个菜单,用户在列表中选择一个菜单(1-3),然后要求用户输入一个字符串(取决于所选菜单),该字符串应作为输入读取并打印出来安慰。但是在执行脚本时,我发现了这个错误。这可能有什么问题?

~] # perl sample.pl

Global symbol "$user" requires explicit package name at ./sample.pl line 26.
Global symbol "$user" requires explicit package name at ./sample.pl line 27.
Global symbol "$user" requires explicit package name at ./sample.pl line 28.
Global symbol "$process" requires explicit package name at ./sample.pl line 37.
Global symbol "$process" requires explicit package name at ./sample.pl line 38.
Global symbol "$process" requires explicit package name at ./sample.pl line 39.
Missing right curly or square bracket at ./sample.pl line 52, at end of line
syntax error at ./sample.pl line 52, at EOF
Execution of ./sample.pl aborted due to compilation errors.

#!/usr/bin/perl

use strict;
use warnings;
use Switch;

my $input = '';

while ($input ne '3')
{
clear_screen();

print "1. user\n".
      "2. process\n".
      "3. exit\n";

print "Enter choice: ";
$input = <STDIN>;
chomp($input);

{
    case '1'
 {

print "Enter user";
$user =  <STDIN>;
chomp ($user);
print "User is  $user\n";

  }

    case '2'
 {
 print "Enter process:";
 $process =  <STDIN>;
 chomp ($process);
 print "Process is $process\n";
    }
  }

1 个答案:

答案 0 :(得分:1)

如果您使用perltidy格式化代码,则可以轻松看到有一个无与伦比的括号:

#!/usr/bin/perl
use warnings;

my $input='';

while ( $input ne '3' ) {
    clear_screen();

    print "1. user\n" . "2. process\n" . "3. exit\n";
    print "Enter choice: ";
    $input=<STDIN>;
    chomp($input);
    {   ## <-- this open brace is probably the culprit of the error

        if ( $input eq '1' ) {
            print "Enter user";
            $user=<STDIN>;
            chomp($user);
            print "User is  $user\n";
        }
        else {
            print "Enter process:";
            $process=<STDIN>;
            chomp($process);
            print "Process is $process\n";
        }
    }

代码格式化不只是让代码看起来不错;它还可以更容易地追踪错误并让其他人理解。您还应该在所有脚本上use strict;,以确保在代码中出现问题之前捕获潜在的编程错误。