CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Win32 Programming Help: Re: [PapaGeek] Class or Package?: Edit Log



Laurent_R
Veteran / Moderator

Feb 23, 2014, 3:18 AM


Views: 32690
Re: [PapaGeek] Class or Package?


In Reply To
What I need is a variable that remains defined from one call to a sub to the next, but restricted to that sub or file alone, not visible outside the sub/file. The only way to do this is with a package, but that makes the dialog loop extremely complicated to implement.


This can be done without any problem (see below).


In Reply To
“Perl got this one wrong from version 1 and onwards. The default variable scope in Perl 5 is the “package variable”, a kind of global variable. Define something inside a block; still see it outside.”

Not true if you use strictures and lexical ("my") variables.


In Reply To
It looks like Perl missed the boat on that one. In order for a variable to remain defined it must be global and available to all subs at the same time.


Not so.

See http://perldoc.perl.org/perlfaq7.html#How-do-I-create-a-static-variable? : starting with Perl 5.10, "the state declaration creates the lexical variable that persists between calls to the subroutine."


Code
sub counter { state $count = 1; $count++ }

In this example, the $count variable is set to 1 the first time and is then icremented. The counter function "remembers" the value of $count from one call to the next.

Another way to obtain the same result (available with older versions of Perl) is to use closures:


Code
{ 
my $count = 0;
sub counter { return $count++;}
}
print counter(), "\n" for (1..10);


which prints:

Code
0 
1
2
3
4
5
6
7
8
9


For more information on closures: http://perldoc.perl.org/perlfaq7.html#What%27s-a-closure?


(This post was edited by Laurent_R on Feb 23, 2014, 3:19 AM)


Edit Log:
Post edited by Laurent_R (Veteran) on Feb 23, 2014, 3:19 AM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives