I disagree. Here is the full code and FETCH is only called once for each element within the body of the loop:
use strict;
use warnings;
package MyClass;
use Tie::Array;
our @ISA = ('Tie::Array');
our @data;
# mandatory methods
sub TIEARRAY { my $class = shift; bless \@data, $class; @data = @_
+; return \@data }
sub FETCH { print "FETCH: "; my ($self, $index ) = @_; return $dat
+a[$index] }
sub FETCHSIZE { print "<FETCHSIZE> "; return scalar @data }
package main;
for( @{ tie my @x, "MyClass", "first", "second"; \@x } ) {
print "In loop = ";
print "$_\n";
}
Output:
In loop = FETCH: first
In loop = FETCH: second
| [reply] [d/l] [select] |
Ah sorry, I stand corrected. I was reading your code as:
for( do { tie my @x, "MyClass", "first", "second"; @x } ) {
So indeed:
for( @{ tie my @x, "MyClass", "first", "second"; \@x } ) {
will make for() iterate over a tied array. In fact,
use strict;
use warnings;
package MyClass;
use Tie::Array;
our @ISA = ('Tie::Array');
our @data;
# mandatory methods
sub TIEARRAY { my $class = shift; bless \@data, $class; @data = @_
+; return \@data }
sub FETCH { print "FETCH: "; my ($self, $index ) = @_; return $dat
+a[$index] }
sub FETCHSIZE { return scalar @data }
package main;
sub wrapper {
tie my @x, "MyClass", @_;
\@x;
}
for( @{wrapper("first", "second")} ) {
print "In loop = ";
print "$_\n";
}
also works. So it's quite close to what I want, yay. Any improvement is welcome :-)
| [reply] [d/l] [select] |
sub wrapper : lvalue {
tie my @x, "MyClass", @_;
@x;
}
for( wrapper("first", "second") ) {
print "In loop = ";
print "$_\n";
}
As I said initially I am not expert in this, so there might be undesired side effects...
And FETCHSIZE is called once only...
| [reply] [d/l] |