Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^4: Getting for() to accept a tied array in one statement

by perlancar (Hermit)
on Apr 16, 2019 at 14:10 UTC ( [id://1232658]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Getting for() to accept a tied array in one statement
in thread Getting for() to accept a tied array in one statement

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 :-)

Replies are listed 'Best First'.
Re^5: Getting for() to accept a tied array in one statement
by hdb (Monsignor) on Apr 16, 2019 at 14:18 UTC

    Try this:

    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...

      hdb, you're my hero :-) My faith in Perl is restored again.

        Why do you want to make something so simple so complicated and expensive? Use an iterator!

        sub make_list_iterator { my @list = @_; return sub { return () if !@list; return shift(@list); }; } my $iter = make_list_iter("some", "el", "ems"); while ( my ($item) = $iter->() ) { ... }

        As a bonus, one doesn't need to know the length of the list in advance with an iterator!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (1)
As of 2024-04-15 21:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found