From the course: Perl 5 Essential Training
Unlock the full course today
Join today to access over 22,500 courses taught by industry experts or purchase this course individually.
Static variables - Perl Tutorial
From the course: Perl 5 Essential Training
Static variables
- [Voiceover] Beginning with Perl 5.10, you can create static variables with the state feature. Here is a working copy of func.pl from chapter ten of the exercise files. So I'm gonna come down here to my function, and I'm going to declare a variable. And then I'm going to increment that variable and print it, saying "say ++$n" like that. And so that will increment n, so instead of 10, it will be 11, and it'll pass that 11 to "say", and when I run it, you see it says 11. Now here is the interesting thing. If I run this function five times, each time we get a new copy of n, which is discarded at the end of the block. And so, each time it'll print the number 11. So I'll run this, and you see we get number 11 five times. On the other hand, if instead of "my" I use the keyword "state", now we have a static variable instead of a dynamic variable. And when I run this, you notice that the value increases each time. So this is what's called a static variable. Instead of there being a new copy…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.