Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Index of Items in Array using foreach loop

by tobyink (Abbot)
on Feb 22, 2013 at 10:50 UTC ( #1020131=note: print w/replies, xml ) Need Help??

in reply to Index of Items in Array using foreach loop

Don't loop through the array; loop through the indices!

use strict; use warnings; my @SampleArray = ("one", "two", "three"); for my $ArrayIndex ( 0 .. $#SampleArray ) { printf( "%s is at location %d in the array\n", $SampleArray[$ArrayIndex], $ArrayIndex, ); }

Or just use a sufficiently modern version of Perl...

use v5.12; use strict; use warnings; my @SampleArray = ("one", "two", "three"); while (my ($ArrayIndex, $ArrayItem) = each @SampleArray) { printf( "%s is at location %d in the array\n", $ArrayItem, $ArrayIndex, ); }

Update: Although each @array was only added to Perl as of 5.12, Array::Each::Override provides a working implementation of each @array for Perl going back to 5.8.

package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1020131]
[Corion]: Meh. I think I have now the parts down that I want from a simple Javascript frontend for single-page- applications with a aPerl backend. But it seems that all Javascript templating modules either don't support two-way binding (which would be nice) or ...
[Corion]: ... don't support server-side precompilation (which means the client has to compile all templates to Javascript themselves), or are giant frameworks that expect to do everything (which is not what I want)
[Corion]: I feel that there is a talk somewhere in there, either about the structure and parts, or how I used several parts to get a complete whole.
[Corion]: Maybe I can still find something that is compatible with handlebars.js (which has JS precompilation) but allows for two-way data binding (which is great for the UI)

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2017-03-30 07:44 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (355 votes). Check out past polls.