Schrift
[thread]12888[/thread]

Konstruktor mit einer Hashliste die ein Array beinhaltet? (Seite 2)

Leser: 2


<< |< 1 2 >| >> 17 Einträge, 2 Seiten
MGlutaeus
 2008-12-11 11:37
#117075 #117075
User since
2008-12-10
5 Artikel
BenutzerIn
[default_avatar]
Danke soweit :)

Aber das mit der globalen Variable "our" klappt nicht,
die möchte wohl einfach nicht von ausserhalb angesprochen werden!

Was mach ich da syntaktisch falsch?
Gast Gast
 2008-12-11 13:23
#117085 #117085
Code: (dl )
$cell::cellCount = $cell::cellCount + 1;
schribt man besser so:
Code: (dl )
$cellCount++;
Es ist nicht nötig den Namespacenamen mit aufzurfen, wenn du im selben Namespace bist. du macht ja auch nicht "$main::test='abc';"
und wenn du den Aufruf explizit machen willst solltest du besser "__PACKAGE__::" benutzen.

Aber ansich keine Anung was nicht funktioniert, zu wenig information en, was sagt "use warnings"? Keine Meldung? Meldungen?
Alles richtig geschrieben?
Was steht zu welchen Zeitpunkt in der Variable?
Wass soll drin zu welchen Zeitpunkt drin stehen?
Gibt es ein Minimalbeispiel bei dem der Fehler auftritt?
pktm
 2008-12-11 13:45
#117089 #117089
User since
2003-08-07
2921 Artikel
BenutzerIn
[Homepage]
user image
Am besten, du bearbeitest deinen Code nochmal, fügst überall noch use warnings; ein (auch in den Modulen) und schreibst die Sache nochmal hier rein.
Dann kann ich auch nochmal nach dem Konstruktor sehen.
http://www.intergastro-service.de (mein erstes CMS :) )
MGlutaeus
 2008-12-11 22:33
#117107 #117107
User since
2008-12-10
5 Artikel
BenutzerIn
[default_avatar]
Ok ich poste dann mal den Gesamtcode vom meinem
kurzen "LawinenSimulator"-Programm
den kann man übrigens auch in andere Sachen
umbauen und eine Schlacht zw zwei Manschen simulieren oder
ein Tetrisspiel machen oder damit Space Invader etc.
schon ne coole Sache, wenn's endlich mal in Perl laufen würde :/
(habs vorher in Java gemacht und versuch es zu transkribieren,
aber meine Perlfähigkeiten reichen (noch) nicht ganz...)

index.pl

Code (perl): (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use strict;
use ca;
use cell;
use warnings;

$sandHeap = ca->new(5,1,20,'0.0','0','0.0');

while($sandHeap->{iniTime}++ <= $sandHeap->{finTime}) {

        my $rndCell = $sandHeap->getRandomCell();
        $rndCell->increaseCellValue();
        print $sandHeap->toString();

        while($sandHeap->isInstable()){
                $sandHeap->doTransition();
                print $sandHeap->toString();
        }

}



ca.pm

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package ca;
use strict;
use cell;
use warnings;

         our $instability=4;

        sub new {
         my $class = shift;
         my @cellList = {};
         my $this = {
             dim => shift,
             iniTime => shift,
             finTime => shift,
             rndInit => shift,
             useNorth => shift,
             useDiagnoal => shift,
             cellList => [@cellList]
         };
         bless ($this, $class);
         $this->addCells();
         $this->addCellsNeighbors();

         return $this;
        }

         sub addCells{
          my $this = shift;
           my $rnd=0; my $i=0;
                for($i=1; $i<=($this->{dim})*($this->{dim}); $i++){
                        if($this->{rndInit}){ $rnd = rand($instability-1); }
                       push($this->{cellList}, Cell->new($rnd));
                }
        }


         sub addCellsNeighbors {
          my $this = shift;
                foreach($this->{cellList}) {
                        $_->addNeighbors($this->{dim},$this->{useNorth},$this->{useDiagonal});
                }
        }


         sub doTransition {
          my $this = shift;
                foreach($this->{cellList}) { $_->calcCell($this); }
                foreach($this->{cellList}) { $_->updateValue(); }
        }


         sub isInstable {
          my $this = shift;
                foreach($this->{cellList}) {
                        if($_->getCellValue() >= $ca::instability){
                                return '0.0';
                        }
                }
                return '0';
        }


         sub getRandomCell {
          my $this = shift;
                my $rnd = 1+int(rand($cell::cellCount));                return $this->getCellByIndex($rnd);
        }

         sub getCellByIndex {
          my $this = shift; my $index = shift;
                foreach($this->{cellList}) {
                        if($_->{index}==$index) { return $_; }
                }
                return undef;
        }


         sub getSumOfCellValues {
          my $this = shift;
                my $sumOfCellValues=0;
                foreach($this->{cellList}) {
                        $sumOfCellValues += $_->getCellValue(); }
                return $sumOfCellValues;
        }

         sub toString(){
          my $this = shift;
                my $string = "Step ".(($this->{iniTime})-1).": ";
                $string .= $this->getSumOfCellValues()." sand corns.";

                if($this->isInstable()) { $string .= "Avalanche alarm!"; }

                foreach($this->{cellList}) {
                        SWITCH: {
                            $_==0 && do { $string .= ". "; last SWITCH; };
                            $_==1 && do { $string .= "° "; last SWITCH; };
                            $_==2 && do { $string .= "o "; last SWITCH; };
                            $_==3 && do { $string .= "O "; last SWITCH; };
                            $_==4 && do { $string .= "X "; last SWITCH; };
                                     do { $string .= "X "; last SWITCH; };
                        }
                        if(($_->{index})%$this->{dim}==0) { $string .= "\n"; }
                }
                return $string;
        }
1;


cell.pm

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cell;

use ca;
use strict;
use warnings;

        our $cellCount=0;

        sub new {
         my $class = shift;
         my @neighbourCells = {};
         my $this = {
             value => shift,
             valueAfter => 0,
             index => $cellCount++,
             neighbourCells => [@neighbourCells]
         };
         bless ($this, $class);
         return $this;
        }

         sub getCellValue {
          my $this = shift;
                return $this->{value};
        }


         sub increaseCellValue {
          my $this = shift;
                $this->{value}++;
        }

         sub calcCell {
          my $this = shift; my $ca = shift;
                if($this->{value} < $ca::instability){
                        # same value, if nothing happens
                        $this->{valueAfter} = $this->{value};
                        # check for instable neighbors
                        foreach($this->{neighbourCells}){
                                # increase per instable neighbor
                                if($ca->getCellByIndex($_)->{value} >= $ca::instability){
                                        $this->{valueAfter} = $this->{value}+1;
                                }
                        }
                }
                # set 0 if instable
                else { $this->{valueAfter}=0; }
        }


         sub updateValue {
          my $this = shift;
                $this->{value} = $this->{valueAfter};
                $this->{valueAfter} = 0;
        }


         sub addNeighbors {
          my $this = shift; my $dim = shift; my $useNorth = shift; my $useDiagonal = shift;

                my $TS; my $LS; my $RS; my $BS;
                if($this->{index}<$dim+1)           { $TS = '0.0';} else {$TS = '0';}   # is on top side
                if(($this->{index}+$dim-1)%$dim==0) { $LS = '0.0';} else {$LS = '0';}  # is on left side
                if((($this->{index})%($dim))==0)    { $RS = '0.0';} else {$RS = '0';}  # is on right side
                if($this->{index}>($dim*$dim)-$dim) { $BS = '0.0';} else {$BS = '0';}  # is on bottom side

                if(!$TS)              { array_push($this->{neighbourCells}, $this->{index}-$dim);}
                if(!$LS)              { array_push($this->{neighbourCells}, $this->{index}-1);    }
                if(!$RS)              { array_push($this->{neighbourCells}, $this->{index}+1);     }
                if(!$BS & $useNorth)  { array_push($this->{neighbourCells}, $this->{index}+$dim);   }

                if($useDiagonal){
                        if(!$TS&!$LS) { array_push($this->{neighbourCells}, $this->{index}-$dim-1);  }
                        if(!$TS&!$RS) { array_push($this->{neighbourCells}, $this->{index}-$dim+1);   }
                        if($useNorth){
                                if(!$BS&!$LS)   { array_push($this->{neighbourCells}, $this->{index}+$dim-1);}
                                if(!$BS&!$RS)   { array_push($this->{neighbourCells}, $this->{index}+$dim+1); }
                        }
                }
        }
1
pktm
 2008-12-12 12:45
#117120 #117120
User since
2003-08-07
2921 Artikel
BenutzerIn
[Homepage]
user image
Ok, nochmla ganz wichtig: Array deklariert man mit *runden* Klammern:
Code: (dl )
1
2
3
my @array = ();
my @array2 = qw(1 2 4 5);
print $array2[0]; # Zugriff mit $


Hashes auch:
Code: (dl )
1
2
3
4
5
my %hash = ();
my %h2 = (
key => 'value',
);
print $h2{'key'}; # Zugriff mit $ und dem Schlüssel


Hashreferenzen deklariert man mit geschweiften Klammern:
Code: (dl )
1
2
3
4
5
my $hashref = {};
my $hashref2 = {
key => 'value',
};
print $hashref->{'key'}; # Zugriff mit $ + Dereferenzierung (->).


Arrays kannst du nicht in einem Hash als Wert speichern. Aber du kannst eine Referenz darauf speichern:
Code: (dl )
1
2
3
4
5
6
my @a = qw(1 2 3);
my %h = (
'key' => \@a,
);

print $h{'key'}->[0]; # Gibt das 1. Element von @a aus.


Zu Referenzen musst du dir perldoc perlref durchlesen. Da kommst du nicht drumherum. Das ist so grundlegend wie Variablenzuweisung.

Konstruktoren sind in Perl nicht vordefiniert, genausowenig this. Wenn du eine Methode aufrufst:
Code: (dl )
$objekt->method();


dann ist das erste Argument des Aufrufs das, was links vom -> steht, nämlich $objekt. Und das ist auch das, was du immer als erstes in den Methoden auslesen solltest:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
=head2 method()

Deine Beschreibung der Methode. Funktioniert so ähnlich wie Doxygen, nennt sich aber POD.

=cut

sub method {
my $self = shift; # hier kommt deine Instanz, das links neben dem ->.

# TODO...

} # /method


Den Zugriff auf Klassenvariablen ohne Akzessor finde ich so hässlich wie das Wort Akzessor :)
Hier mein Vorschlag:
Code: (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
package Ca; # Großbuchstabe vorne dran!
use strict;
use warnings;
use base qw(Class::Accessor);
__PACKAGE__->mk_accessors(qw(instability));

#our $instability = 4; # wird im Konstruktor gesetzt.

=head1 METHODS

=head2 new( $dimension, $iniTime, $finTime, $rndInit, $useNorth, $useDiagonal )

TODO: Deine Beschreibung des Objetes, das man mit new() konstruiert, hier.

=cut

sub new {
my $class = shift;
my ( $dimension, $iniTime, $finTime, $rndInit, $useNorth, $useDiagonal ) = @_;

# TODO: Prüfen der Argumente

my @cellList = ();

my $some_data = {
dim => $dimension,
iniTime => $iniTime,
finTime => $finTime,
rndInit => $rndInit,
useNorth => $useNorth,
useDiagnoal => $useDiagonal,
cellList => \@cellList,
# alternativ: anonyme Arrayreferenz
#cellList => [],
};

my $self = bless ($some_data, $class);

# init instability:
$self->instability(4);
# get this value anywhere else by calling my $inst = $obj->instability();

$self->addCells();
$self->addCellsNeighbors();

return $self;
} # /new

1; # Semikolon dran!
http://www.intergastro-service.de (mein erstes CMS :) )
pq
 2008-12-12 14:31
#117121 #117121
User since
2003-08-04
12209 Artikel
Admin1
[Homepage]
user image
pktm: deklarieren muss man hashes und arrays nur mit my. die klammern gehören jeweils zur initialisierung, nicht zur deklaration. genaugenommen.
Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. -- Damian Conway in "Perl Best Practices"
lesen: Wiki:Wie frage ich & perlintro Wiki:brian's Leitfaden für jedes Perl-Problem
pktm
 2008-12-12 15:53
#117124 #117124
User since
2003-08-07
2921 Artikel
BenutzerIn
[Homepage]
user image
pq+2008-12-12 13:31:40--
pktm: deklarieren muss man hashes und arrays nur mit my. die klammern gehören jeweils zur initialisierung, nicht zur deklaration. genaugenommen.


Korrekt, aber
Code: (dl )
my @array = {};


ist falsch, wenn man ein leeres Array deklarieren möchte. Und um es menschen, die mit Perl anfangen leicht zu machen, habe ich die Informationen nach bestem Gewissen reduziert :)
http://www.intergastro-service.de (mein erstes CMS :) )
<< |< 1 2 >| >> 17 Einträge, 2 Seiten



View all threads created 2008-12-10 16:36.