Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to iterator array in order?

0 views
Skip to first unread message

Peng Yu

unread,
Nov 20, 2008, 11:39:04 PM11/20/08
to
Hi,

I know at least three ways to iterator an array. But I'm not sure if
the first two iteration methods would iterator the array in order
(from the first element to the last element). Can somebody let me
know?

What is the best way to iterator an array?

Thanks,
Peng

#!/usr/bin/perl

@array = (1, 2, 3, 4);

foreach(@array) {
print "$_\n";
}

for my $elem (@array) {
print "$elem\n";
}

for($i = 0; $i <= $#array; ++ $i) {
print "$array[$i]\n";
}

s...@netherlands.com

unread,
Nov 21, 2008, 12:15:13 AM11/21/08
to

Yes, all three would. The 'foreach' is a special,
unrelated case. The target becomes an alias for the
actual element. If you write to the target, you write
to the element, be careful on that one.


sln

Jürgen Exner

unread,
Nov 21, 2008, 12:30:41 AM11/21/08
to
Peng Yu <Peng...@gmail.com> wrote:
>I know at least three ways to iterator an array. But I'm not sure if
>the first two iteration methods would iterator the array in order
>(from the first element to the last element). Can somebody let me
>know?
>What is the best way to iterator an array?

>@array = (1, 2, 3, 4);


>
>foreach(@array) {
> print "$_\n";
>}
>
>for my $elem (@array) {
> print "$elem\n";
>}

That's exactly the same as the first version except that you are using a
different variable ($_ versus $elem). "for" and "foreach" are synonyms.
Which one is better depends only on if you want to use $_ (often as the
default in following operations) or not.

>for($i = 0; $i <= $#array; ++ $i) {
> print "$array[$i]\n";
>}

This does something totally different because it iterates over the
indices of the array.
BTW: if you are using $#array instead of the length of the array then
you probably should also start your iteration with $[ instead of with 0.
The combination you are using doesn't make much sense because your start
value is hardcoded to ignores non-default values for $[ while your end
respects them.

As for your original question: use whatever is is more appropriate for
the task at hand: if you want to iterate over the elements then do so.
If you want to iterate over the indices (sometimes that cannot be
avoided) then iterate over the indices.

jue

Uri Guttman

unread,
Nov 21, 2008, 11:02:07 AM11/21/08
to
>>>>> "s" == sln <s...@netherlands.com> writes:

s> On Thu, 20 Nov 2008 20:39:04 -0800 (PST), Peng Yu <Peng...@gmail.com> wrote:
>> foreach(@array) {
>> print "$_\n";
>> }
>>
>> for my $elem (@array) {
>> print "$elem\n";
>> }
>>
>> for($i = 0; $i <= $#array; ++ $i) {
>> print "$array[$i]\n";
>> }

s> Yes, all three would. The 'foreach' is a special,
s> unrelated case. The target becomes an alias for the
s> actual element. If you write to the target, you write
s> to the element, be careful on that one.

huh? for and foreach are EXACTLY the same in perl - they are aliases for
the same syntax spot. the type of loop is controlled by the presence of
; inside the (). you have either a list loop (the first two examples) or
a c style loop (the last example).

the first two examples are the same except for using $_ vs a
lexical. the 'for' vs 'foreach' there is irrelevent (try it). both alias
each element to the loop variable.

uri

--
Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com --
----- Perl Code Review , Architecture, Development, Training, Support ------
--------- Free Perl Training --- http://perlhunter.com/college.html ---------
--------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com ---------

Peter J. Holzer

unread,
Nov 23, 2008, 6:25:03 AM11/23/08
to
On 2008-11-21 05:30, Jürgen Exner <jurg...@hotmail.com> wrote:
> Peng Yu <Peng...@gmail.com> wrote:
[...]

>>for($i = 0; $i <= $#array; ++ $i) {
>> print "$array[$i]\n";
>>}
>
> This does something totally different because it iterates over the
> indices of the array.
> BTW: if you are using $#array instead of the length of the array then
> you probably should also start your iteration with $[ instead of with 0.
> The combination you are using doesn't make much sense because your start
> value is hardcoded to ignores non-default values for $[ while your end
> respects them.

Frankly, in my world $[ doesn't exist. Anyone who sets it outside of an
obfu, should be drawn and quartered. I won't clutter up my code just
because some idiot might set it. So if I need to iterate over the
indices of an array I use:

for my $i (0 .. $#array) { ... }

hp

Jürgen Exner

unread,
Nov 23, 2008, 12:13:19 PM11/23/08
to
"Peter J. Holzer" <hjp-u...@hjp.at> wrote:
>On 2008-11-21 05:30, Jürgen Exner <jurg...@hotmail.com> wrote:

>> BTW: if you are using $#array instead of the length of the array then
>> you probably should also start your iteration with $[ instead of with 0.
>> The combination you are using doesn't make much sense because your start
>> value is hardcoded to ignores non-default values for $[ while your end
>> respects them.
>
>Frankly, in my world $[ doesn't exist. Anyone who sets it outside of an
>obfu, should be drawn and quartered.

Agreed :-)

>I won't clutter up my code just
>because some idiot might set it. So if I need to iterate over the
>indices of an array I use:
>
> for my $i (0 .. $#array) { ... }

Why not
for my $i (0 .. @array+1)
Doesn't seem to introduce much clutter to me...

jue
>
> hp

s...@netherlands.com

unread,
Nov 23, 2008, 2:11:26 PM11/23/08
to
On Fri, 21 Nov 2008 11:02:07 -0500, Uri Guttman <u...@stemsystems.com> wrote:

>>>>>> "s" == sln <s...@netherlands.com> writes:
>
> s> On Thu, 20 Nov 2008 20:39:04 -0800 (PST), Peng Yu <Peng...@gmail.com> wrote:
> >> foreach(@array) {
> >> print "$_\n";
> >> }
> >>
> >> for my $elem (@array) {
> >> print "$elem\n";
> >> }
> >>
> >> for($i = 0; $i <= $#array; ++ $i) {
> >> print "$array[$i]\n";
> >> }
>
> s> Yes, all three would. The 'foreach' is a special,
> s> unrelated case. The target becomes an alias for the
> s> actual element. If you write to the target, you write
> s> to the element, be careful on that one.
>
>huh? for and foreach are EXACTLY the same in perl - they are aliases for
>the same syntax spot. the type of loop is controlled by the presence of
>; inside the (). you have either a list loop (the first two examples) or
>a c style loop (the last example).
>
>the first two examples are the same except for using $_ vs a
>lexical. the 'for' vs 'foreach' there is irrelevent (try it). both alias
>each element to the loop variable.
>
>uri

Really good to know. I will try it, I will put it on the queue of 10,000
other things to try. Until I do, I must take your word for it and be sure
to not asign to $_ unless inside a while() loop. Sound good?

$@_,$_,$_[n] still got me cornfused.

sln

s...@netherlands.com

unread,
Nov 23, 2008, 2:21:41 PM11/23/08
to
On Thu, 20 Nov 2008 20:39:04 -0800 (PST), Peng Yu <Peng...@gmail.com> wrote:

^^
Don't do this here, it just looks bad.
As a C++ programmer, you know the problems with
compiler optimizations on pre-increment.

In Perl its ok, no such thing as optimizations.
$i = ++$i is ok.

sln

John W. Krahn

unread,
Nov 23, 2008, 2:31:32 PM11/23/08
to
Jürgen Exner wrote:
> "Peter J. Holzer" <hjp-u...@hjp.at> wrote:
>> On 2008-11-21 05:30, Jürgen Exner <jurg...@hotmail.com> wrote:
>
>>> BTW: if you are using $#array instead of the length of the array then
>>> you probably should also start your iteration with $[ instead of with 0.
>>> The combination you are using doesn't make much sense because your start
>>> value is hardcoded to ignores non-default values for $[ while your end
>>> respects them.
>> Frankly, in my world $[ doesn't exist. Anyone who sets it outside of an
>> obfu, should be drawn and quartered.
>
> Agreed :-)
>
>> I won't clutter up my code just
>> because some idiot might set it. So if I need to iterate over the
>> indices of an array I use:
>>
>> for my $i (0 .. $#array) { ... }
>
> Why not

Why not indeed!

> for my $i (0 .. @array+1)
> Doesn't seem to introduce much clutter to me...

Just errors. :(


John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall

s...@netherlands.com

unread,
Nov 23, 2008, 3:06:15 PM11/23/08
to
On Sun, 23 Nov 2008 11:31:32 -0800, "John W. Krahn" <som...@example.com> wrote:

>Jürgen Exner wrote:
>> "Peter J. Holzer" <hjp-u...@hjp.at> wrote:
>>> On 2008-11-21 05:30, Jürgen Exner <jurg...@hotmail.com> wrote:
>>
>>>> BTW: if you are using $#array instead of the length of the array then
>>>> you probably should also start your iteration with $[ instead of with 0.
>>>> The combination you are using doesn't make much sense because your start
>>>> value is hardcoded to ignores non-default values for $[ while your end
>>>> respects them.
>>> Frankly, in my world $[ doesn't exist. Anyone who sets it outside of an
>>> obfu, should be drawn and quartered.
>>
>> Agreed :-)
>>
>>> I won't clutter up my code just
>>> because some idiot might set it. So if I need to iterate over the
>>> indices of an array I use:
>>>
>>> for my $i (0 .. $#array) { ... }
>>
>> Why not
>
>Why not indeed!
>
>> for my $i (0 .. @array+1)
>> Doesn't seem to introduce much clutter to me...
>
>Just errors. :(
>
>
>John

Errors?
asdf:>> for my $i (0 .. @array+1)

Give an example please.

sln

Martien Verbruggen

unread,
Nov 23, 2008, 3:25:09 PM11/23/08
to

$ perl -wl
my @foo = (1, 2, 3);
print "\$#foo and \@foo + 1 are ",
($#foo == @foo + 1) ? "" : "not ",
"the same";
__END__

Martien
--
|
Martien Verbruggen | life ain't fair, but the root password
| helps. -- BOFH
|

s...@netherlands.com

unread,
Nov 23, 2008, 3:38:49 PM11/23/08
to
On Mon, 24 Nov 2008 07:25:09 +1100, Martien Verbruggen <mg...@heliotrope.com.au> wrote:

>On Sun, 23 Nov 2008 20:06:15 GMT,
> s...@netherlands.com <s...@netherlands.com> wrote:
>> On Sun, 23 Nov 2008 11:31:32 -0800, "John W. Krahn"
>> <som...@example.com> wrote:
>>

[snip]


>>>> for my $i (0 .. @array+1)
>>>> Doesn't seem to introduce much clutter to me...
>>>
>>>Just errors. :(
>>>
>>>
>>>John
>> Errors?
>> asdf:>> for my $i (0 .. @array+1)
>
>$ perl -wl
>my @foo = (1, 2, 3);
>print "\$#foo and \@foo + 1 are ",
> ($#foo == @foo + 1) ? "" : "not ",
> "the same";
>__END__
>
>Martien

Who said $#foo and \@foo + 1 are the same amount??
for my $i (0 .. @array+1)...

'@array+1' is just a number. Any other errors?

sln

Martien Verbruggen

unread,
Nov 23, 2008, 4:01:06 PM11/23/08
to
On Sun, 23 Nov 2008 20:38:49 GMT,

s...@netherlands.com <s...@netherlands.com> wrote:
> On Mon, 24 Nov 2008 07:25:09 +1100, Martien Verbruggen
> <mg...@heliotrope.com.au> wrote:
>
>>On Sun, 23 Nov 2008 20:06:15 GMT,
>> s...@netherlands.com <s...@netherlands.com> wrote:
>>> On Sun, 23 Nov 2008 11:31:32 -0800, "John W. Krahn"
>>> <som...@example.com> wrote:
>>>
> [snip]
>>>>> for my $i (0 .. @array+1)
>>>>> Doesn't seem to introduce much clutter to me...
>>>>
>>>>Just errors. :(
>>>>
>>>>
>>>>John
>>> Errors?
>>> asdf:>> for my $i (0 .. @array+1)
>>
>>$ perl -wl
>>my @foo = (1, 2, 3);
>>print "\$#foo and \@foo + 1 are ",
>> ($#foo == @foo + 1) ? "" : "not ",
>> "the same";
>>__END__
>>
>>Martien
>
> Who said $#foo and \@foo + 1 are the same amount??

Jürgen Exner did, implicitly. He wrote the first bit of code above (you
snipped the attribution, but left that code), in response to someone
else writing a loop with $#array, in code that I quoted in the previous
message, but that you snipped.

> for my $i (0 .. @array+1)...
>
> '@array+1' is just a number. Any other errors?

But it's the wrong number for this context. Not all numbers are
equivalent in all contexts.

Even without the original code, @array + 1 is an index that is too high
by two for the size of the array it's supposed to be indexing.

I don't see any other errors, but I think this error on its own is
enough to be commented on.

Martien
--
|
Martien Verbruggen | Never hire a poor lawyer. Never buy from a
| rich salesperson.
|

s...@netherlands.com

unread,
Nov 23, 2008, 6:26:57 PM11/23/08
to

There was no context mentioned. I got no problem with
the range. In fact, in my opinion,
for my $i (0 .. @array+65535)
is way better than
for my $i (0 .. $#array)

it clearly states the truth about the size of arrays !!
Have a nice day!


sln

Martien Verbruggen

unread,
Nov 23, 2008, 7:29:29 PM11/23/08
to
On Sun, 23 Nov 2008 23:26:57 GMT,
s...@netherlands.com <s...@netherlands.com> wrote:
> There was no context mentioned. I got no problem with

There was. Please check the thread.

> the range. In fact, in my opinion,
> for my $i (0 .. @array+65535)
> is way better than
> for my $i (0 .. $#array)
>
> it clearly states the truth about the size of arrays !!

That is just plain silly.

Martien
--
|
Martien Verbruggen | In the fight between you and the world, back
| the world - Franz Kafka
|

Jürgen Exner

unread,
Nov 23, 2008, 9:03:14 PM11/23/08
to
"John W. Krahn" <som...@example.com> wrote:
>Jürgen Exner wrote:
>> "Peter J. Holzer" <hjp-u...@hjp.at> wrote:
>>> On 2008-11-21 05:30, Jürgen Exner <jurg...@hotmail.com> wrote:
>>> for my $i (0 .. $#array) { ... }
>>
>> Why not
>
>Why not indeed!
>
>> for my $i (0 .. @array+1)
>> Doesn't seem to introduce much clutter to me...
>
>Just errors. :(

Well, yeah, fine, whatever.

s/+/-/

I guess it was pretty obvious what I meant. If you want to make a big
deal out of that typo, then be my guest.

jue

Charlton Wilbur

unread,
Nov 24, 2008, 8:43:52 AM11/24/08
to
>>>>> "J" == Jürgen Exner <jurg...@hotmail.com> writes:

J> I guess it was pretty obvious what I meant. If you want to make a
J> big deal out of that typo, then be my guest.

But the fact that an experienced, knowledgeable Perl programmer can so
easily typo that is a sign that it's a dangerous construct to use.

Charlton


--
Charlton Wilbur
cwi...@chromatico.net

Ted Zlatanov

unread,
Nov 24, 2008, 10:35:07 AM11/24/08
to
On Sun, 23 Nov 2008 18:03:14 -0800 Jürgen Exner <jurg...@hotmail.com> wrote:

JE> "John W. Krahn" <som...@example.com> wrote:
>> Jürgen Exner wrote:
>>> "Peter J. Holzer" <hjp-u...@hjp.at> wrote:
>>>> On 2008-11-21 05:30, Jürgen Exner <jurg...@hotmail.com> wrote:
>>>> for my $i (0 .. $#array) { ... }
>>>
>>> Why not
>>
>> Why not indeed!
>>
>>> for my $i (0 .. @array+1)
>>> Doesn't seem to introduce much clutter to me...
>>
>> Just errors. :(

JE> Well, yeah, fine, whatever.

JE> s/+/-/

JE> I guess it was pretty obvious what I meant. If you want to make a big
JE> deal out of that typo, then be my guest.

The typo's existence is relevant, though: if you, an experienced
programmer, made it, surely beginners will do it too. IMO array offsets
should be a last resort, and very few algorithms need them. I usually
get by with iterating through the list elements, which generates cleaner
code in the vast majority of the cases (and sometimes even improves the
algorithm because it forces me to think differently about it).

Array offsets and memory management are the naughty bits of
programming. They should be covered up in public whenever possible :)

Ted

Jürgen Exner

unread,
Nov 24, 2008, 11:11:46 AM11/24/08
to
Ted Zlatanov <t...@lifelogs.com> wrote:
>IMO array offsets
>should be a last resort, and very few algorithms need them. I usually
>get by with iterating through the list elements, which generates cleaner
>code in the vast majority of the cases (and sometimes even improves the
>algorithm because it forces me to think differently about it).

I very strongly agree.
However for that instance the question was what to use if you do need
the indices after all, e.g. to loop through multiple lists in sync or
access multiple elements in each iteration.

jue

Ted Zlatanov

unread,
Nov 24, 2008, 11:59:52 AM11/24/08
to
On Mon, 24 Nov 2008 08:11:46 -0800 Jürgen Exner <jurg...@hotmail.com> wrote:

JE> Ted Zlatanov <t...@lifelogs.com> wrote:
>> IMO array offsets
>> should be a last resort, and very few algorithms need them. I usually
>> get by with iterating through the list elements, which generates cleaner
>> code in the vast majority of the cases (and sometimes even improves the
>> algorithm because it forces me to think differently about it).

JE> I very strongly agree.
JE> However for that instance the question was what to use if you do need
JE> the indices after all, e.g. to loop through multiple lists in sync or
JE> access multiple elements in each iteration.

I know, I just couldn't resist a chance to say "naughty bits" in a
technical context ;)

Ted

0 new messages