[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Elementary question (I think)



At 9:57 AM -0600 3/11/99, Chris Nandor wrote:
>At 10.46 -0500 1999.03.11, Chris Sansom wrote:
>>Oops - I think I sent this to the wrong address. Try again...
>
>The old address is aliased to the new, so no worries.
>
>>Suppose I have an array @stuff, when can and can't I use this syntax:
>>
>>for ($i = 0; $i <= @stuff, $i++) {
>>...
>>}
>>
>>I was under the impression that this was perfectly safe, but it seems to
>>break my script. As soon as I change all those @'s in this type of
>>construct to $# it works just fine.
>
>@array is the number of elements in @array.  $#array is the last index of
>@array.
>
>@array = (0..9);
># scalar @array now is 10
># $#array now is 9
>
>You want the last index, so you want 9.  You can also do this, however:
>
>for my $i (0 .. $#array) {
>
>
>}

I would add that you can also use your original syntax, provided you
haven't changed $[ (and you shouldn't - that's deprecated).  You need to
change one thing, though - you need to say "$i < @stuff" rather than "$i <=
@stuff".  The <= breaks your script because on the last time through the
loop it uses an array index which is one greater than the biggest one.

I'm only pointing this out because I find @stuff more readable than
$#stuff.  To each their own.

Regards,

Dave
 ____________________________________________________________
| Dave Lorand, Programmer/Analyst   | davel@src.uchicago.edu |
| Social Science Research Computing | 773-702-3792           |
| University of Chicago             | 773-702-2101 (fax)     |
+-----------------------------------+------------------------+
 ---> finger davel@cicero.src.uchicago.edu for my PGP key <--

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org