perl - How do I properly declare global variable? -


all,

consider piece of code:

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>; } 

the last print statement not want print variable. if declare 'our' or comment declaration out. what's more weird happens on first iteration. file has couple of thousand records , on first iteration variable undefined. subsequent calls good.

any idea going on?

thank you.

you haven't provided enough information replicate problem ourselves, case first line of file not contain properly-formatted data whatever $year you're dealing with. perhaps first line header?

another possibility $year may not set on first pass through while loop, never enter of if blocks set $classwork , gets set @ later point in loop. since don't show or how $year set, can't whether issue or not.

to best possible answers, it's best provide complete, runnable example code demonstrates issue little additional code possible. (in experience, such examples no more 15-20 lines.) benefit of doing discover problem while in process of finding smallest possible program demonstrates it.

also, there no evident reason why $classwork needs global. changing our my in current declaration should not affect of code you've shown , consider moving my $classwork inside while loop, unless there's intended condition under shouldn't reassigned on every pass , should instead retain value 1 iteration next.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -