jQuery Chat

前にmtgでjQueryが話題に上がったので、調べてると、

Jquery+PHPによる簡易AJAXチャット作りに挑戦してみた - 遥か彼方の彼方から

があったので、そのままPHPPerlに変えてみた。

Perl : Ajax Chat

特に何かを施したとかはないです。

参考というかそのままです。

jQueryはこれから勉強...


修正した箇所だけ以下に

index.html

 元:$.get('./chat/write.php'
 後:$.get('./chat/write.cgi'
 元:load("./chat/read.php");
 後:load("./chat/read.cgi");


read.cgi

#!/usr/bin/perl

use strict;
use CGI;

my $q = CGI->new;

print $q->header(-charset=>'utf-8'); 

my $logfile = "chat.log";

my $i = 0;
open(my $fh,"<",$logfile) or die $!;
while(my $line = <$fh>){
    chomp $line;
    $line = &htmlspecialchars($line);
    print "<dl>";
    if($i%2 == 0){ # 名前 
	print qq{<dt class="name">$line</dt>};
    }else{ # 発言
	print qq{<dd class="msg">$line</dd>};
    }
    print "</dl>";
    $i++;
}
close($fh);

sub htmlspecialchars () {
    my $str = shift;
    $str =~ s/\&/\&amp\;/g;
    $str =~ s/\"/\&quot\;/g;
    $str =~ s/\</\&lt\;/g;
    $str =~ s/\>/\&gt\;/g;
    return $str;
}

1;


write.cgi

#!/usr/bin/perl

use strict;
use CGI;

my $q = CGI->new;

print $q->header(-charset=>'utf-8');

my $logfile = "chat.log";

my $name = $q->param("name");
my $msg = $q->param("msg");

open(my $fh,">>",$logfile) or die $!;
print $fh "$nameの発言:\n$msg\n";
close($fh);

1;

はてな記法に慣れるまで時間かかりそう...


参考:

phpのhtmlspecialcharsと同等の処理をperlで行い結果を配列で返す Script Source Sample for Perl