P is for Practical PerlMonks

### find the element position of \$scalar

 on Feb 08, 2002 at 07:58 UTC Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

foreach \$scalar (@array){ >>>> find the element position of \$scalar <<<< }

Replies are listed 'Best First'.
Re: find the element position of \$scalar
by jmcnamara (Monsignor) on Feb 08, 2002 at 08:48 UTC

```my \$i = 0;

foreach my \$scalar (@array) {
print \$scalar, " is at position ", \$i++, "\n";
}

--
John.

Re: find the element position of \$scalar
by &nbsp;&nbsp; (Sexton) on Feb 08, 2002 at 08:50 UTC

```my \$i=0;
foreach \$scalar(@array) {
print("\$scalar is \$i element\n");
\$i++;
}
or, shorter:
```my \$i=0;
for(@array) {
print("\$_ is \$i element\n");
\$i++;
}

The white hole.

Gotit! Thanks to both of you... :-) Lucie Luvsya
Re: find the element position of \$scalar
by &nbsp;&nbsp; (Sexton) on Feb 08, 2002 at 08:01 UTC

```for(my \$i=0;\$i<@array;\$i++) {
print("\$array[\$i] is the \$i element\n");
}

The white hole.

Thanks for the quick reply, however I need the results inclosed within the foreach statement as shown above.
Re: find the element position of \$scalar
by tadman (Prior) on Feb 08, 2002 at 14:11 UTC
Here's a few quick bits of code.

Indexed iteration:
```foreach my \$i (0..\$#array)
{
print "\$i: \$array[\$i]\n";
}
Regular iteration with incremented tracker:
```my \$i = 0;
foreach my \$e (@array)
{
print "\$i: \$e\n";
\$i++;
}
Old-school C-style method:
```for (my \$i = 0; \$i < @array; \$i++)
{
print "\$i: \$e\n";
}
In this case, I'd say the first is "better" since it requires less code.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://144060]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2022-05-26 07:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Do you prefer to work remotely?

Results (93 votes). Check out past polls.

Notices?