[Purdue-pm] Code Question

Dave Jacoby jacoby at purdue.edu
Tue May 24 13:20:30 PDT 2011


-----8<-- The Code ------------------------------------------------
#!/usr/bin/perl
use strict ;
use warnings ;

my $index = 9 ;
for ( 1 .. 5 ) { foo() ; }
print qq{OUTSIDE: $index \n};

{
     my $index = 0 ;
     sub foo {
         print qq{INDEX: $index \n} ;
         $index++ ;
         }
     }

-----8<-- Expected Outcome ----------------------------------------
INDEX: 0
INDEX: 1
INDEX: 2
INDEX: 3
INDEX: 4
OUTSIDE: 9

-----8<-- Real Outcome --------------------------------------------
Use of uninitialized value $index in concatenation (.) or string at 
/home/jacoby/sub_test.pl line 12.
INDEX:
INDEX: 1
INDEX: 2
INDEX: 3
INDEX: 4
OUTSIDE: 9

-----8<-- Question ------------------------------------------------

If I comment out "$index = 0 ;", it uses the $index in the global scope.

I've seen this trick before. Make a block, put a variable and a 
subroutine in the block. The subroutine is the only place you can see 
the variable, but the variable exists outside of the subroutine, giving 
it more permanence. I got it to work like I want by using a BEGIN{} 
block but I don't recall having to do that before.

What magic bit of syntax am I missing? Or have I blocked the trauma of 
having to use a BEGIN block?

-- 
Dave Jacoby                         Address: WSLR S049
Code Maker                          Mail:    jacoby at purdue.edu
Purdue University                   Phone:   765.49.67368
    1049 days until the end of XP support



More information about the Purdue-pm mailing list