Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

how can i get the index value of array during runtime

by phemal (Sexton)
on Mar 02, 2007 at 10:05 UTC ( [id://602850]=perlquestion: print w/replies, xml ) Need Help??

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

i want to print the index of an @array during runtime. How do i do that ???
@array =qw (34 56 78 9); foreach (@array) { here i want to print the index of array }
Thanks in advance Hemal

Replies are listed 'Best First'.
Re: how can i get the index value of array during runtime
by davorg (Chancellor) on Mar 02, 2007 at 10:20 UTC
Re: how can i get the index value of array during runtime
by Samy_rio (Vicar) on Mar 02, 2007 at 10:16 UTC

    Hi phemal, try using Array::Each module,

    use strict; use warnings; use Array::Each; my @x = qw( p e r l ); my $one = Array::Each->new( \@x ); while( my( $x, $i ) = $one->each() ) { printf "%3d: %s\n", $i, $x; }
    TIMTOWDI

    Otherwise,

    use strict; use warnings; my @x = qw( p e r l ); for my $index (0..$#x){ print "$index : $x[$index]\n"; }

    Update: Also refer (RFC) Arrays: A Tutorial/Reference

    Regards,
    Velusamy R.


    eval"print uc\"\\c$_\""for split'','j)@,/6%@0%2,`e@3!-9v2)/@|6%,53!-9@2~j';

Re: how can i get the index value of array during runtime
by derby (Abbot) on Mar 02, 2007 at 10:17 UTC
    #!/usr/bin/perl use strict; use warnings; my @array =qw (34 56 78 9); for( my $i = 0; $i <= $#array; $i++ ) { print $i, " ", $array[$i], "\n"; }
    -derby

    update: Changed to $i <= $#array (thanks rminner).

Re: how can i get the index value of array during runtime
by siva kumar (Pilgrim) on Mar 02, 2007 at 10:19 UTC
    Will the below program solve your issue??
    @array =qw (34 56 78 9); $index = 0; foreach (@array) { print "$index \t $_ \n"; $index++; }

      If an "index" is required use $index as the identifier. If a count is required you need to pre-increment the value or set it to 1 initially.

      Yes, I know it is trivial sample code that doesn't matter, but good habits are worth acquiring. And distinguishing between a (1 based) count and a (0 based) index is a habit well worth acquiring!


      DWIM is Perl's answer to Gödel
        Gladly accepted your point ..
        :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://602850]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-03-29 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found