Re: comma puzzle
- From: Ben Morrow <ben@xxxxxxxxxxxx>
- Date: Sun, 20 Jul 2008 23:45:04 +0100
Quoth Nick Wedd <nick@xxxxxxxxxxxxx>:
In message <slrng86i28.chm.tadmc@xxxxxxxxxxxxxxxxxxxxx>, Tad J McClellan
<tadmc@xxxxxxxxxxxxxx> writes
There are *two* variables named $i in your code.
"my $i=1" and "print $i" refer to the lexical variable named $i.
"$i<10" and "$i++" refer to the package variable named $i (ie. $main::i).
I see. I have been in the habit of writing things like
for ( my $suit=0 ; $suit<4 ; $suit++ )
and assuming they did the same as
my $i;
for ( $suit=0 ; $suit<4 ; $suit++ )
This is not the case Tad was talking about. The semicolons make the
three parts of a C-style for loop separate statements, so the 'my $i'
introduced by the first is available in the others. It's only the
Perl-style loop (with commas, so the whole list is a single statement)
that will use a variable from an outer scope.
Your first example is better than your second. In the first, the
variable $i is scoped to (all iterations of) the for loop; in the
second, $i is still visible after the loop is over. The first is more
like
{
my $suit = 0;
for ($suit = 0; $suit < 4; $suit++) {
...
}
}
except Perl doesn't actually have to create an extra block. Since it's
always better to keep a variable's scope as small as possible, the first
should be preferred when you don't need to get at the index outside the
loop.
Better still would be
for my $suit (0..3) { ... }
since it's much clearer to see which values the index will be iterating
over.
Ben
--
For far more marvellous is the truth than any artists of the past imagined!
Why do the poets of the present not speak of it? What men are poets who can
speak of Jupiter if he were like a man, but if he is an immense spinning
sphere of methane and ammonia must be silent? [Feynmann] ben@xxxxxxxxxxxx
.
- References:
- comma puzzle
- From: Nick Wedd
- Re: comma puzzle
- From: Tad J McClellan
- Re: comma puzzle
- From: Nick Wedd
- comma puzzle
- Prev by Date: Re: how to change the effective UID
- Next by Date: Re: sha1 -- core
- Previous by thread: Re: comma puzzle
- Next by thread: Re: comma puzzle
- Index(es):
Relevant Pages
|