home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Perl CookbookPerl CookbookSearch this book

10.3. Creating Persistent Private Variables

10.3.2. Solution

Wrap the function in another block, then declare my variables in that block's scope rather than in the function's:

{
    my $variable;
    sub mysub {
        # ... accessing $variable
    }
}

If the variables require initialization, make that block an INIT so the variable is guaranteed to be set before the main program starts running:

INIT {
    my $variable = 1;                       # initial value
    sub othersub {                          
      # ... accessing $variable
    }
}


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.