Thread Hash als Schleifenbedingung in Schleife ändern (4 answers)
Opened by bianca at 2010-08-10 20:00

bianca
 2010-08-10 20:00
#140515 #140515
User since
2009-09-13
6990 Artikel
BenutzerIn

user image
Guten Abend!
Hab eine Schleife, die über die Keys iteriert (heißt das in diesem Fall so?). Nun ändere ich in der Schleife den Hash und die Schleife kommt aus dem Tritt.
Kann ich innerhalb der Schleife etwas tun, um dem Schleifenkopf die neuen Bedingungen beizubringen und nach 2 => bar mit 3 => mor fortzufahren?

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/perl -w
use strict;
use warnings;
use diagnostics;

my %hash = (
    0=>'nul',
    1=>'foo',
    2=>'bar',
    3=>'max',
    4=>'mor',
    5=>'zig',
);

foreach my $nr (
    sort {$a <=> $b}
    grep {$_ > 1}
    keys %hash
) {
    if ($nr == 3) {
        %hash = (   
        # diese Neudefinition entspricht einer Löschung von key '3/max'
        # zur Laufzeit der Schleife mit neuer Nummerierung der nachfolgenden Keys
        # Warum kommt die Schleife aus dem Tritt?
            0=>'nul',
            1=>'foo',
            2=>'bar',
            3=>'mor',
            4=>'zig',
        );
        $nr --;
        next;
    }
    print $nr . ' => ' . $hash{$nr} . "\n";
}

__AUSGABE__
2 => bar
4 => zig
Use of uninitialized value in concatenation (.) or string at test14.pl line 34 (#1)
    (W uninitialized) An undefined value was used as if it were already
    defined.  It was interpreted as a "" or a 0, but maybe it was a mistake.
    To suppress this warning assign a defined value to your variables.

    To help you figure out what was undefined, perl will try to tell you the
    name of the variable (if any) that was undefined. In some cases it cannot
    do this, so it also tells you what operation you used the undefined value
    in.  Note, however, that perl optimizes your program and the operation
    displayed in the warning may not necessarily appear literally in your
    program.  For example, "that $foo" is usually optimized into "that "
    . $foo, and the warning will refer to the concatenation (.) operator,
    even though there is no . in your program.

5 =>
10 print "Hallo"
20 goto 10

View full thread Hash als Schleifenbedingung in Schleife ändern