Re: comma puzzle




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
.



Relevant Pages

  • Re: load data from Access to SQL
    ... > If I can speak in simplistic terms, what I'd like to do is the following: ... > Is something like this possible without having to loop through every record ... > Thanks, Andre ...
    (microsoft.public.vb.database.ado)
  • Re: Jump Take offs
    ... Being taught the loop as we speak (without any success to report as ...
    (rec.sport.skating.ice.recreational)
  • Re: load data from Access to SQL
    ... If I can speak in simplistic terms, what I'd like to do is the following: ... Is something like this possible without having to loop through every record ... Thanks, Andre ...
    (microsoft.public.vb.database.ado)
  • Re: access attributes from record
    ... Is it possible to determine the 'Length of a record, loop ... it an get attribute name/value/type? ... I can't speak for the others on this group---but personally, ... pseudo-Ada code that isn't really Ada at all, ...
    (comp.lang.ada)
  • Re: Coffee Tourism in Columbia
    ... It's just English and punctuation that throws you for a loop. ... that's a great idea, jack! ... i speak good french, ...
    (alt.coffee)