in reply to Re^3: why each/keys/values can't work on slice? (updated)
in thread why each/keys/values can't work on slice?

use feature qw/say/; my @bb = 1..10; while(my ($ind, $val) = each @bb){ say "ind is $ind"; if($ind >5){ while(my ($inner_ind, $inner_val) = each @bb){ say "inner ind is $inner_ind, inner val is $inner_v +al" } } } # will endless loop since while share one iterator while(my ($ind, $val) = each @bb){ say "ind is $ind"; } # this will quit loop successfully.
I don't understand why every array has to have only one iterator, please enlighten me. and guess each/keys doesn't work on slice would be relative to this reason?

Replies are listed 'Best First'.
Re^5: why each/keys/values can't work on slice? (updated)
by LanX (Saint) on Jan 11, 2023 at 05:45 UTC
    > > maybe show us an example from another language w/o "this limitation" to learn from? :)

    these are not examples from another language demonstrating no "limitations"... :)

    anyway in Perl 5.36 you can do this

    use v5.36; use warnings; use experimental qw/for_list/; my %hash; @hash{"a".."e"} = 1..5; for my ($key, $value) ( %hash{"c","a","e"} ) { say "$key -> $value"; }

      $ perl /d/perl/pm/iterate_hash_slice.pl c -> 3 a -> 1 e -> 5

    Cheers Rolf
    (addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
    Wikisyntax for the Monastery

Re^5: why each/keys/values can't work on slice? (updated)
by ikegami (Patriarch) on Jan 11, 2023 at 19:07 UTC

    I don't understand why every array has to have only one iterator

    First of all, it's one more than needed.

    for my $ind ( 0 .. $#bb ) { say "ind is $ind"; }

    And to answer your question, it's the maximum you can have. If you want multiple iterators, they necessarily have to be external to the array.

    For example, in C#, you have to create an external iterator.

    using ( var enumerator = list.GetEnumerator() ) { while ( enumerator.MoveNext() ) { var item = emumerator.current; // ... } }

    Nothing stops you from doing the same in Perl.

    Now, C# does have syntactical sugar that makes this cleaner.

    for ( var item in list ) { // ... }

    Again, nothing stops you from doing the same in Perl.

    If no one's done it, I guess it's not that useful. (I'm not saying noone's done it. I have no idea.)