From the course: Perl 5 Essential Training

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Locally scoped variables

Locally scoped variables - Perl Tutorial

From the course: Perl 5 Essential Training

Start my 1-month free trial

Locally scoped variables

- [Voiceover] If you've been following the course in sequence, you've probably noticed that we have been declaring variables with the my keyword. This provides lexical scoping, where the variable is local to a block of code. Here's a working copy of function.pl from Chapter 10 of the Exercise Files. A my variable has scope that's local to a block of code, so if I declare a variable here, the block of code is actually the file. It's important to know that in Perl, a block is either enclosed in curly braces like this function body, or a file, so if we declare a my variable outside of a function, its scope is the whole file. So I'm gonna say my $x = 42, and inside the function, I'll say, "x is $x" and when I run this, you see it says x is 42, which is what we would expect. Now, if we declare a my variable inside the function with exactly the same name, now when I run it, you notice that the value is taken from the x that's declared inside the function and not the one that's declared…

Contents