Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Automatic Loop Counter not in perl

by Joost (Canon)
on Aug 21, 2007 at 10:50 UTC ( #634050=note: print w/ replies, xml ) Need Help??


in reply to Automatic Loop Counter not in perl

One thing I don't like about your proposed variable is that as far as I can see, you'd have to do additional assignment of the $LOOPCOUNTER variable if you want to nest loops.

I prefer the way more "functional/OO" languages like javascript and ruby implement foreach loops using callbacks with explicit parameters. Something that's easy to implement in perl for fullblown objects:

$list->foreach( sub { my ($element,$index) = @_; print "$index $element\n"; });
If perl's prototypes would work for methods, you could build something very close to ruby's
list.each_with_index { |element,index| print "#{index} #{element}\n" };

For completeness, here's the javascript version:

array.forEach(function(element,index) { document.write(index+" "+element+"\n"); // depending on the host });
Note that ruby & javascript's versions also have the advantage of being easily overridable for any object (including "standard arrays", since both allow methods to be attached to objects instead of only to "object types" / classes - and, of course, in both languages arrays are always "real" objects).

updated: fixed typo, slight cleanup of wording.


Comment on Re: Automatic Loop Counter not in perl
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://634050]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2014-12-26 14:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls