2013-04-10 110 views
0

我经历了几次讨论以找到解决方案,但似乎没有一个人在我的情况下工作。定义全局符号(错误)

我有以下的代码

print ("Choose from the following\n"); 
print ("op1 op2\n"); 

my $x = <>; 
chomp($x);  
print ("x is $x"); 

if ($x eq "op1") 
{ 
my $DirA = "./A"; 
my $DirB = "./B"; # **I want to use this dirA and dir B below (Tried switch stmts but I 
#**get the same error)** 
} 

opendir my($dh), "$DirA" or die "Couldn't open dir DirA!"; 
my @files = readdir $dh; 
closedir $dh; 
system("rm -rf diffs"); 
system ("mkdir diffs\n"); 
foreach my $input (@list) { 
. 
. 
. 
} 

我得到这个错误:全局符号“$迪拉”要求在test_switch.tc明确包名

是否有人可以帮助我的相同。我的意图是将选项/开关添加到我的脚本中。像“test.pl -A”,“test.pl -B”,我开始使用case stmt。请就此提供意见。

+0

你可以使用perl模块吗?如果是这样,我建议你考虑使用[Getopt :: Long](http://search.cpan.org/~jv/Getopt-Long-2.39/lib/Getopt/Long.pm)。它会让你的生活变得更轻松。 – David 2013-04-10 00:17:20

回答

2

$DirA$DirB不是全局性的,他们只在他们用my宣布if声明的范围界定。一般来说,从the documentation开始:“A my将列出的变量声明为本地(词汇)到封闭块,文件或eval。”要在下面的任何代码使用它们,你必须做一些事情,如:

my $DirA; 
my $DirB; 

if ($x eq "op1") { 
    $DirA = "./A"; 
    $DirB = "./B"; 
} else { 
    $DirA = ... 
    $DirB = ... 
} 

注意else:你也应该做一些事情,如果$x"op1"因为它代表即使代码有运行试图将未定义的值传递给opendir时会发生错误。

+0

谢谢。现在,我添加了这个错误后,如果($ x eq“op1”){ my $ DirA =“./A”; my $ DirB =“./B”; } else { my $ DirA =“./C”; my $ DirB =“./D”; } opendir my($ dh),“$ DirA”或死“无法打开目录DirA!”;在test_switch.tc第47行<>行1处使用未初始化的值。 无法打开dir DirA!在test_switch.tc第47行,<>行。这是opendir行 – Rancho 2013-04-10 00:30:05

+0

不要把'my'放在'if'和'else'里面。这将屏蔽在块外定义的相同名称的变量。为了确保一切正常,在'opendir'之前'print'DirA = $ DirA和DirB = $ DirB \ n“'。 – miorel 2013-04-10 00:45:02

+0

谢谢!它的作品:) – Rancho 2013-04-10 01:45:18

2

只需在之前声明变量即可,if块之后便可以访问它们。

my $DirA; 
my $DirB; 

if ($x eq "op1") { 
    $DirA = "./A"; 
    $DirB = "./B"; 
} 
+0

谢谢:)这工作! – Rancho 2013-04-10 01:47:25