[Purdue-pm] Code Question

Rick Westerman westerman at purdue.edu
Tue May 24 13:33:52 PDT 2011


You have a correct idea but variable and the subroutine need to be declared early before the routine is called.  Or within, as you point out, with a BEGIN statement.



----- Original Message -----
> -----8<-- The Code ------------------------------------------------
> #!/usr/bin/perl
> use strict ;
> use warnings ;
> 
> my $index = 9 ;
> for ( 1 .. 5 ) { foo() ; }
> print qq{OUTSIDE: $index \n};
>

I.e., either put this at the top of your script ... or ... put a BEGIN in front of it.
 
> {
> 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
> 
> _______________________________________________
> Purdue-pm mailing list
> Purdue-pm at pm.org
> http://mail.pm.org/mailman/listinfo/purdue-pm

-- 
Rick Westerman 
westerman at purdue.edu

Bioinformatics specialist at the Genomics Facility.
Phone: (765) 494-0505           FAX: (765) 496-7255
Department of Horticulture and Landscape Architecture
625 Agriculture Mall Drive
West Lafayette, IN 47907-2010
Physically located in room S049, WSLR building



More information about the Purdue-pm mailing list