http://www.perlmonks.org?node_id=1232642

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

To give a context, this question is part of my continuing quest to port Python's tqdm style (see Part 1 here: Porting tqdm to Perl). So basically I want to wrap an array or a list of values in a for() loop like this:

for("some", "el", "ems") { ... }
with some kind of iterator using this syntax:
for (wrapper("some", "elems")) { # some code }

So that for each iteration, as Perl executes some code, each element retrieval also gets to run my code, so I can do something. In the case of tqdm, I want to measure how long some code run so I can give feedback to user on how long the whole loop is going to take. Thus, in essence, adding a progress indicator just by wrapping the list of values given to for().

In Python, this is easy to do because for() already expects an iterator.

In Perl, I can use the array tie mechanism to do this:

tie @ary, "My::Class", "some", "el", "ems"; for (@ary) { some_code($_); }

The order of code being executed will be:

My::Class::TIEARRAY
My::Class::FETCHSIZE
My::Class::FETCH(0) -> "some"
some_code("some")
My::Class::FETCHSIZE
My::Class::FETCH(1) -> "el"
some_code("el")
My::Class::FETCHSIZE
My::Class::FETCH(2) -> "ems"
some_code("ems")

So far so good. However, I also want a nice syntax like in the Python version. Condensing the above syntax to what I want is still not possible: for (tie @ary, "My::Class", "some", "el", "ems") { ... } # NOPE

This makes for() only loops over a single value, the tied object.

for (do { tie @ary, "My::Class", "some", "el", "ems"; @ary }) { ... } # NOPE

This will FETCH() all elements first before giving them to for().

Any ideas? So far I'm thinking of creating a custom C<for()> function.

EDIT: Added some clarification/additional explanation.