Jump to content

Scope modifiers: Difference between revisions

→‎{{header|Perl}}: Reintegrated the discussion of 'state'.
(→‎{{header|R}}: substantially expanded discussion)
(→‎{{header|Perl}}: Reintegrated the discussion of 'state'.)
Line 289:
By default, an unqualified name refers to a package variable in the current package. The current package is whatever you set it to with the last <code>package</code> declaration in the current lexical scope, or <code>main</code> by default. But wherever stricture is in effect, using a name that would be resolved this way is a compile-time error.
 
There are three kinds of declaration that can influence the scoping of a particular variable: <code>our</code>, <code>my</code>, <code>state</code>, and <code>local</code>. <code>our</code> makes a package variable lexically available. Its primary use is to allow easy access to package variables under stricture.
 
<lang perl>use strict;
Line 316:
print "$fruit\n"; # Prints "orange"; refers to $Bar::fruit.
# The first $fruit is inaccessible.</lang>
 
<code>state</code> is like <code>my</code> but creates a variable only once. The variable's value is remembered between visits to the enclosing scope. The <code>state</code> feature is only available in perl 5.9.4 and later, and must be activated with <code>use feature 'state';</code> or a <code>use</code> demanding a sufficiently recent perl.
 
<lang perl>use 5.10.0;
 
sub count_up{
{
state $foo = 13;
say $foo++;
 
count_up; # Prints "13".
count_up; # Prints "14".</lang>
 
<code>local</code> gives a package variable a new value for the duration of the current ''dynamic'' scope.
Line 326 ⟶ 339:
}
 
phooey; # Prints "llama".
 
sub do_phooey
Line 334 ⟶ 347:
}
 
do_phooey; # Prints "alpaca".
phooey; # Prints "llama".</lang>
 
Usually, <code>my</code> is preferrable to <code>local</code>, but one thing <code>local</code> can do that <code>my</code> can't is affect the special punctuation variables, like <code>$/</code> and <code>$"</code>. Actually, in perl 5.9.1 and later, <code>my $_</code> is specially allowed and works as you would expect.
 
In perl 5.10.0, a new Modifier <code>state</code> was intoduced. It can only be used with the 'feature' pragma, or an <code>use 5.01</code> (or greater).
A Variable introduced with <code>state</code> has no Dynamic scope, thus it doesn't change or vanish like one introduced with <code>my</code>.
 
<lang perl>
sub count_up{
state $foo;
$foo++;
</lang>
 
=={{header|PicoLisp}}==
845

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.