|Pathologically Eclectic Rubbish Lister|
Getting for() to accept a tied array in one statementby perlancar (Pilgrim)
|on Apr 16, 2019 at 11:10 UTC||Need Help??|
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:
with some kind of iterator using this syntax:
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:
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")