我在Perl編程作業,要求我做到以下幾點:如何用Perl構建一個家族樹?
創建在MySQL數據庫中的表,並插入這些記錄到其中:
負載從表中的數據到Son類的實例數組中。
使用該數組創建表示父子樹的HTML代碼,並將該html代碼打印到STDOUT。沒有必要讓樹看起來不錯。這樣的事情就可以了:
tree http://i25.tinypic.com/314t177.png
我跑出來的想法,請幫助。我的代碼如下:
#!/usr/bin/perl
use strict;
use Son;
use CGI;
use Data::Dumper;
use DBI;
my $q = new CGI;
#DB connect vars
my $user = "##";
my $pass = "##";
my $db = "##";
my $host = "localhost";
my $dsn = "DBI:mysql:database=$db;host=$host";
my $dbh = DBI->connect($dsn,$user,$pass);
eval { $dbh->do("DROP TABLE sons") };
print "Drop failed: [email protected]\n" if [email protected];
$dbh->do("CREATE TABLE sons (son VARCHAR(30) PRIMARY KEY, father VARCHAR(30))");
my @rows = (["bill", "sam"],
["bob", ""],
["jack", "sam"],
["jone", "mike"],
["mike", "bob"],
["sam", "bob"]
);
for my $i (0 .. $#rows) {
$dbh->do("INSERT INTO sons (son, father) VALUES (?,?)", {}, $rows[$i][0], $rows[$i][1]);
}
our @sons_array;
my $sth = $dbh->prepare("SELECT * FROM sons");
$sth->execute();
while (my $ref = $sth->fetchrow_hashref()) {
$sons_array[++$#sons_array] = Son->new($ref->{'son'}, $ref->{'father'});
}
$sth->finish();
$dbh->disconnect();
print $q->header("text/html"),$q->start_html("Perl CGI");
print "\n\n";
constructFamilyTree(@sons_array, '');
print $q->end_html;
sub constructFamilyTree {
my @sons_array = @_[0..$#_ -1];
my $print_father;
my $print_son;
my $print_relation;
my $current_parent = @_[$#_];
my @new_sons_array;
my @new_siblings;
#print $current_parent."\n";
foreach my $item (@sons_array){
if(!$item->{'son'} || $item->{'son'} eq $item->{'father'}) { # == ($item->{'son'} eq '')
print "\n List contains bad data\n";
return 0;
}
if($item->{'father'} eq $current_parent) {
my $temp_print_relation;
foreach my $child (@sons_array) {
if($child->{'father'} eq $item->{'son'}) {
if(!$temp_print_relation) {
$temp_print_relation .= ' |';
}
else {
$temp_print_relation .= '-----|';
}
}
}
$print_relation .= $temp_print_relation." ";
$print_son .= '('.$item->{'son'}.') ';
@new_siblings[++$#new_siblings] = $item;
$print_father = $item->{'father'};
}
else {
$new_sons_array[++$#new_sons_array] = $item;
}
}
print $print_son. "\n". $print_relation."\n";
#print $print_father."\n";
#print $print_relation . "\n". $print_son;
foreach my $item (@new_siblings) {
constructFamilyTree(@new_sons_array, $item->{'son'});
}
}
perl module:
#File Son.pm, module for class Son
package Son;
sub new {
my($class, $son, $father) = @_;
my $self = {'son' => $son,
'father' => $father};
bless $self, $class;
return $self;
}
1;
「用盡想法」,想法到底是什麼?這裏沒有任何問題,只是你的任務,和「在這裏,去爲我做」。 – 2009-07-10 01:26:28
你的問題確實不是關於CGI或MySQL。這是關於選擇和顯示適當的數據結構。你的代碼中包含了太多的多餘的細節。 – 2009-07-10 06:01:03
只是想知道我是否完全脫離正確的軌道。對不起/感謝。 – 2009-07-10 14:23:46