timothy adigun wrote:

On 8/29/12, John W. Krahn<jwkr...@shaw.ca>  wrote:
timothy adigun wrote:

On 8/29/12, timothy adigun<2teezp...@gmail.com>   wrote:

for(my $i=0; $i<= length(@startSite)-1; $i++) {

    The above could be:
      for(my $i=0; $i<= scalar (@startSite); $i++) {
        ...

for(my $i=0; $i<= scalar (@startSite); $i++) {  ## Oops

for(my $i=0; $i<= scalar (@startSite)-1; $i++) {  ## working

First, length(@startSite) is WRONG so s/could/should/ and second, that
is usually written as:


Agreed that  length(@startSite) is WRONG and I didn't say otherwise,

You also didn't explain to the beginners on this list as to why it is wrong. (Because an array in scalar context evaluates to the number of elements in the array, and the length of a number has nothing to do with the contents of an array or the index of an array element.)


but not "scalar (@startSite)".

That COULD be wrong, depending on the value of $[. It is more correct to use $#startSite which is there for the express purpose of defining the last index of the array @startSite.


If the OP decides to use C style of for loop, this is CORRECT:

    for( my $i=1; $i<= scalar (@startSite); $i++ ){ ...

Arrays usually start at 0, not 1 (see $[ in perldoc perlvar) and the use of scalar() in scalar context is redundant.


for my $i ( 0.. $#startSite ) {

The foreach keyword is actually a synonym for the for keyword, so one
can use either.
Please check this: http://perldoc.perl.org/perlsyn.html

You should have the documentation installed on your computer along with perl. See:

perldoc perlsyn


Note: foreach my $i (@startSite){...} will also do the same,

No, there $i will be aliased to each element of @startSite in turn while in the previous examples $i contains the index of each element in turn.

except
that in the "context" of the OP script, the array index is needed.



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to