-2

全部,

考虑这段代码:

our $classwork = 0;
while( <INFILE> )
{
    chomp;
    next if $. == 1;
    if( $year >= 1992 && $year <= 1995 )
    {
        $classwork = (split( /,/ ))[6];
        print "Classwork is: ", $classwork, "\n";
    }
    if( $year >= 1996 && $year <= 2001 )
    {
        $classwork = (split( /,/ ))[-1];
    }
    print "Classwork is: ", $classwork, "\n";
    if( $year == 2002 )
    {
        $classwork = (split( /,/ ))[-2];
    }
    if( $year == 2003 || $year == 2004 )
    {
        $classwork = (split( /,/ ))[23];
    }
    if( $year >= 2005 && $year <= 2009 )
    {
        $classwork = (split( /,/ ))[22];
    }
    if( $year >= 2010 && $year <= 2012 )
    {
        $classwork = (split( /,/ ))[20];
    }
    print "Classwork is: ", $classwork, "\n";
    $line = <STDIN>;
}

最后一个打印语句不想打印变量。即使我将其声明为“我们的”或只是将声明注释掉。更奇怪的是它只发生在第一次迭代中。该文件有几千条记录,在第一次迭代中只有变量未定义。所有后续调用都很好。

知道发生了什么吗?

谢谢你。

4

1 回答 1

0

You haven't provided enough information for us to replicate the problem for ourselves, but the most likely case is that the first line of the file does not contain properly-formatted data for whatever $year you're dealing with. Perhaps the first line is a header?

Another possibility is that $year may not be set on the first pass through the while loop, so you never enter any of the if blocks which set $classwork and then it gets set at a later point in the loop. Since you don't show where or how $year is set, we can't say whether this could be the issue or not.

To get the best possible answers, it's generally best to provide complete, runnable example code which demonstrates your issue with as little additional code as possible. (In my experience, such examples are usually no more than 15-20 lines.) Another benefit of doing this is that you will often discover the problem for yourself while in the process of finding the smallest possible program which demonstrates it.

Also, there is no evident reason why $classwork needs to be global. Changing our to my in its current declaration should not affect any of the code you've shown and I would definitely consider moving my $classwork to be inside the while loop, unless there's some intended condition under which it shouldn't be reassigned on every pass and should instead retain its value from one iteration to the next.

于 2013-08-16T10:47:06.370 回答