Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

find the element position of $scalar

by Anonymous Monk
on Feb 08, 2002 at 07:58 UTC ( [id://144060]=perlquestion: print w/replies, xml ) 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.

Log In?
Username:
Password:

What's my password?
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?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-04-26 03:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found