perl - 条件数组声明

时间:2015-07-27 20:27:59

标签: arrays perl conditional

Perl问题对你们所有人。我有以下代码:

#! /usr/local/bin/perl
use warnings;
use strict;
use Switch;

our @ITEMS_ARRAY = qw ( a b c );

foreach my $i (0 .. $#ITEMS_ARRAY) {
  switch ($ITEMS_ARRAY[$i]) {
    case "a" { print "a\n" }
    case "b" { print "b\n" }
    case "c" { print "c\n" }
  }
}

工作正常。我需要设置" @ ITEMS_ARRAY"某些情况不同。如下所示:

#! /usr/local/bin/perl
use warnings;
use strict;
use Switch;

our $X = 1;

if ($X) {
  our @ITEMS_ARRAY = qw ( a b c );
} else {
  our @ITEMS_ARRAY = qw ( e f g );
}

foreach my $i (0 .. $#ITEMS_ARRAY) {
  switch ($ITEMS_ARRAY[$i]) {
    case "a" { print "a\n" }
    case "b" { print "b\n" }
    case "c" { print "c\n" }
    case "e" { print "e\n" }
    case "f" { print "f\n" }
    case "g" { print "g\n" }
  }
}

但是,我收到以下错误:

Variable "@ITEMS_ARRAY" is not imported at ./r.pl line 14.
Variable "@ITEMS_ARRAY" is not imported at ./r.pl line 15.
Global symbol "@ITEMS_ARRAY" requires explicit package name at ./r.pl line 14.
Global symbol "@ITEMS_ARRAY" requires explicit package name at ./r.pl line 15.
Execution of ./r2.pl aborted due to compilation errors.

非常感谢任何帮助!

谢谢!

1 个答案:

答案 0 :(得分:1)

our是块范围的。您需要在块外部声明,以便变量在外部作用域中可见。

our $X = 1;
our @ITEMS_ARRAY;

if ($X) {
  @ITEMS_ARRAY = qw ( a b c );
} else {
  @ITEMS_ARRAY = qw ( e f g );
}