Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is "my" faster than "local" in Perl?

Tags:

perl

Quoting from PerlMonks: The difference between my and local,

But in real life, they work virtually the same? Yes. Sort of. So when should you use them?

Use my when you can (it's faster than local) ...

I know the lexical vs dynamic scoping difference between my and local, as discussed in this SO thread, but I am not sure why my is "faster".

What exactly do we mean when we say that a my variable is faster than a local variable in Perl?

like image 745
Lazer Avatar asked Aug 30 '10 19:08

Lazer


People also ask

What is the difference between my and local in Perl?

The short answer is that my marks a variable as private in a lexical scope, and local marks a variable as private in a dynamic scope.

What is $/ in Perl?

$/ and $. Note that changing $/ alters Perl's definition of a record and therefore it alters the behavior of $. . $. doesn't actually contain the current line number, it contains the current record number. So in our quotes example above, $. will be incremented for each quote that you read from the filehandle.

How do I declare a global variable in Perl?

Global variables can directly use and are accessible from every part of the program. Example 1: The variable $name is declared at the beginning of the code. It will be visible till the end of the file everywhere. Even inside blocks.


1 Answers

Using local on a variable means that its previous state needs to be pushed onto a stack somewhere and restored again when the local scope is exited. Using my on a variable simply creates an entirely new variable that shadows the previous variable with the same name -- the previous one is entirely untouched, and does not need to be saved anywhere. It is simply lying in wait when the local scope is exited and it is visible again.

This pushing/popping to a stack takes resources; there's a lot of work under the hood to ensure that this works properly. (Consider cases such as an exception being thrown while in local scope, or a signal handler being executed. I'm sure you can think of more.)

Besides being more efficient, using my is much more logical. As a programmer introducing a local variable $foo, you don't need to worry about the semantic reason for the previous version of $foo, what data might already be in it, or indeed if there was a $foo already created. If sometime down the road the earlier declaration of $foo is removed, your local $foo code will break, but my $foo will be perfectly happy. Be a good programmer and keep your code in well-encapsulated pieces, which means using lexical scoping as much as you can. It's quite possible to write a large application and never need variables of package/global scope at all, especially when you use well-designed OO classes.

like image 56
Ether Avatar answered Oct 18 '22 02:10

Ether