Perl变量作用域并在if / else块中使用相同的变量

时间:2013-07-03 20:24:30

标签: perl

我试图找出如何在if / else块中使用相同的变量。例如,

$var1
$var2
$var3

if(condition) {
...
}
else {
...
}

我需要在块中访问$ vars1,2和3,但我不能。我想我有一个范围问题。我尝试将它们设为全局,但我看到很多错误并且程序运行不正常。我错过了什么?

这是我的代码。我的问题是服务器需要底部的变量(@varList等),因为这是一个也使用CGI的apache服务器上的脚本。它吐出这样的错误:

[error] Global symbol "$questionslist" requires explicit package name at /home/megaoff/www/vi
ewquestions.dhtml line 46.\nGlobal symbol "$site" requires explicit package name at /home/megaoff/www/viewquestions.dhtm
l line 46.\nGlobal symbol "$xs" requires explicit package name at /home/megaoff/www/viewquestions.dhtml line 46.\nGlobal
 symbol "$username" requires explicit package name at /home/megaoff/www/viewquestions.dhtml line 46.\n

#!/usr/bin/perl

use strict;
use CGI;
use BarryP;

my $pagev = BarryP::makeP("noextracook", 1);
my $bvga = $pagev->{'vga'};
my %vga = %$bvga;
my $cgi = CGI->new;
my $usePage = "answerquestions.html";
my $anslist = "/home/megaoff/www/limages/anslist.txt";
my $unanslist = "/home/megaoff/www/limages/unanslist.txt";

my $action = $vga{"action"};


if($action eq 'adminmode') {
    my @a_list = $pagev->listFile($anslist);
    my %list = map { split(/\t/, $_, 2) } @a_list;
}   
else {
    my @u_list = $pagev->listFile($unanslist);
    chomp @u_list;
    my %questions = map { $_ => '' } @u_list;
    my $question = $cgi->param('question');
    my $answer = $cgi->param('answer');
    chomp($question, $answer);

    open(my $ANS, '>>', $anslist) or die "Can't open file $anslist: $!";
    print $ANS "$question\t$answer\n";
    close($ANS) or die "Can't close file $anslist: $!";

    delete $questions{$question};
    open(my $UNANS, '>', $unanslist) or die "Can't open file $unanslist: $!";
    print $UNANS "$_\n" foreach keys %questions;
    close($UNANS) or die "Can't close file $unanslist: $!";

    my $questionslist = join("<br>", @u_list);
    my $site = $pagev->{'site'};
    my $xs = $pagev->{'xs'};
    my $username = $pagev->{'username'};
}

my @varList = ('questionslist', $questionslist, 'action', $action, 'site', $site, 'xs', $xs, '$username', $username);

$pagev->pageHeader($usePage, @varList);

2 个答案:

答案 0 :(得分:6)

您的问题在于范围界定。在第46行,当您引用$ questionlist等时,它们已经超出了范围,因为您在else块中定义了它们。

你有(简化):

if ($blah) {
  # do stuff
} else {
  # do other stuff
  my $variable = "something";
}

doSomethingWith($variable); # illegal, $variable is not in scope.

$variable未在else块之外定义,而else块甚至可能不会被执行。您需要将函数放在else块中,或者找到一些方法来赋予这些变量默认值,并在if语句之前声明它们。

答案 1 :(得分:1)

理想情况下,您的变量声明应该具有尽可能最小的范围,同时仍然在需要访问变量的代码范围内。

my $var1 = 'aBcD';
my $var2;
if ($uc) {
   $var2 = uc($var1);
}
else {
   $var2 = lc($var1);
}

当然,这可以写成

my $var1 = 'aBcD';
my $var2 = $uc ? uc($var1) : lc($var1);