f.zz.de
posts /

each vs foreach

Posted Wed 22 Oct 2014 05:02:02 PM CEST
in

Ein spannendes Problem - Eine funktion mit 'each' geschrieben funktioniert nicht. Umgeschrieben mit 'foreach' ist alles gut. Der teufel steckt im detail.

After "each" has returned all entries from the hash or array, the next call to "each" returns the empty list in list context and "undef" in scalar context. The next call following that one restarts iteration. Each hash or array has its own internal iterator, accessed by "each", "keys", and "values". The iterator is implicitly reset when "each" has reached the end as just described; it can be explicitly reset by calling "keys" or "values" on the hash or array. If you add or delete a hash's elements while iterating over it, entries may be skipped or duplicated--so don't do that. Exception: It is always safe to delete the item most recently returned by "each()", so the following code works properly:

D.h. each benutzt einen hash oder array internen iterator. D.h. wenn 'each' schleifen geschachtelt werden kommt da murks bei raus. Anders als offensichtlich bei foreach das einen eigenen iterator benutzt.

Kaputt:

    my @ta=qw/a b c/;
    while(my ($e) = each(@ta)) {
            while(my ($f) = each(@ta)) {
                    printf("e $e f $f\n");
            }
    }

Heile:

    my @ta=qw/a b c/;
    foreach my $e ( @ta ) {
            foreach my $f ( @ta ) {
                    printf("e $e f $f\n");
            }
    }