Variable declaration reset: Difference between revisions
Content added Content deleted
(Realize in F#) |
SqrtNegInf (talk | contribs) (Added Perl) |
||
Line 427: | Line 427: | ||
end |
end |
||
</lang> |
</lang> |
||
=={{header|Perl}}== |
|||
By default, variables can be created on-the-fly, as with <code>$prev</code> here. Testing against <code>$curr</code> is not an error, even when it's value is undefined. This is perhaps not "best practices", but it does work just fine. |
|||
<lang perl>@s = <1 2 2 3 4 4 5>; |
|||
for ($i = 0; $i < 7; $i++) { |
|||
$curr = $s[$i]; |
|||
if ($i > 1 and $curr == $prev) { print "$i\n" } |
|||
$prev = $curr; |
|||
}</lang> |
|||
{{out}} |
|||
<pre>2 |
|||
5</pre> |
|||
But better to do it this way, requiring <code>my</code> declarations imposing lexical scope (an instance of <code>$curr</code> is instantiated on every pass through loop) and employing a <code>state</code> variable (persistent within loop). |
|||
<lang perl>use strict; |
|||
use warnings; |
|||
use feature 'state'; |
|||
my @s = <1 2 2 3 4 4 5>; |
|||
for (my $i = 0; $i < 7; $i++) { |
|||
my $curr = $s[$i]; |
|||
state $prev; |
|||
if ($i > 1 and $curr == $prev) { print "$i\n" } |
|||
$prev = $curr; |
|||
}</lang> |
|||
{{out}} |
|||
<pre>2 |
|||
5</pre> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |