in reply to Re^4: Use of "my" after Perl v5.14
in thread Use of "my" after Perl v5.14
local can generally be implemented manually. The following two are pretty much exactly equivalent.
## Example 1 our $x = "Hello"; sub f { local $x = "Goodbye"; ...; } f(); ## Example 2 our $x = "Hello"; sub f { my $original = $x; $x = "Goodbye"; ...; $x = $original; # restore } f();
local just means that you don't have to remember to manually restore the original value, which can be especially tricky if your sub has several different exit routes (e.g. different return statements in if blocks). Given that local is so much easier than the manual way, there's little reason to go down the manual route. However situations where you need to do this kind of thing are usually pretty rare, and often confined to Perl's built-in variables like $_ and $/.
state is also not especially difficult to handle manually. The following is a reimplementation of my previous "counter" example:
use v5.14; { my $count = 1; sub counter { say $count++; } } counter(); counter(); counter(); counter();
Unlike local there is a valid reason to avoid state. It's a relatively new feature, so if you use it your code will not run on Perl versions prior to 5.10.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Use of "my" after Perl v5.14
by AnomalousMonk (Archbishop) on Sep 21, 2012 at 08:51 UTC | |
|
Re^6: Use of "my" after Perl v5.14
by Rohit Jain (Sexton) on Sep 21, 2012 at 00:02 UTC | |
by AnomalousMonk (Archbishop) on Sep 21, 2012 at 05:00 UTC | |
by Anonymous Monk on Sep 21, 2012 at 02:41 UTC | |
by Anonymous Monk on Sep 21, 2012 at 00:19 UTC | |
by Rohit Jain (Sexton) on Sep 21, 2012 at 00:28 UTC |