Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by Veltro (Hermit)
on Apr 16, 2019 at 13:47 UTC ( [id://1232653] : note . print w/replies, xml ) Need Help??


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

This:

for (tie @ary, "My::Class", "some", "contents";) { ... }

is exactly what you should NOT be doing

Read: Tying-Arrays: If someone outside the class tries to dereference the object returned (doubtless thinking it an ARRAY ref), they'll blow up. This just goes to show you that you should respect an object's privacy.

FETCH and FETCHSIZE are exactly for that you can: 'respect an object's privacy':

Something like this:

my $aryt = tie @ary, "My::Class", "some", "contents"; @ary = ... ; for (0..($aryt->FETCHSIZE-1)) { do-something($aryt->FETCH($_)); }

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

    But isn't the whole point of tie that one can use the tied array as if it were a normal array and all the magic happens without ever calling the classes' methods explicitly?

      Yes, my point is that you simply can't assume an object can be de-referenced to an array. The tie mechanism useful for creating algorithms that can handle objects without implying knowledge about their implementation. Otherwise this would defeat the whole purpose using tie. So it is still a good question, any other solutions appreciated.

        But that statement refers to the reference returned by tie which is not an array reference. The tied array works like a normal array.