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

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

by hdb (Monsignor)
on Apr 16, 2019 at 14:12 UTC ( [id://1232660]=note: print w/replies, xml ) Need Help??


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

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

Replies are listed 'Best First'.
Re^7: Getting for() to accept a tied array in one statement
by Veltro (Hermit) on Apr 16, 2019 at 14:24 UTC

    I don't understand, what you call 'not an array reference' is what I call 'object', so don't we mean the same thing?

    In:

    use ar ; my @ar ; my $art = tie @ar, "ar" ; @ar = (1, 2) ;

    My point is, I cannot know what $art is, so to me this is a big no no:

    my @ar-deref = @{$art};

      Agree. But the following is perfectly ok IMHO

      for(@ar) { print "$_\n"; }
        Yes, that is perfectly fine IMO too
      My point is, I cannot know what $art is, so to me this is a big no no: my @ar-deref = @{$art};

      Yes, I agree that is bad (unless $art overloads @{}), but in the code you showed here, for (tie @ary, "My::Class"), there is no such "bad" de-reference of the return value of tie happening, not even an implicit one. for (tie @ary, "My::Class") { print "$x\n" } will just print something like My::Class=HASH(0x...) - as perlancar said, it's just looping over a one-element list, the return value of tie, and not the elements of @{$art}, as you seemed to be worried about.

        I absolutely agree with that too. I just interpreted a different intent:

        for (tie @ary, "My::Class", "some", "el", "ems") { ... } # NOPE # This makes for() only loops over a single value, the tied object.

        If the intention was to iterate over the 'object' then a possible solution would be to use a de-reference. However I felt this would be a bad idea and decided to point this out.

        But it doesn't matter, everyone has proposed solutions that are much better. Esp. the solution hdb has found now using the lvalue sub is absolutely fantastic.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-03-28 11:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found