Wednesday, June 20, 2007
Thursday, May 10, 2007
Smarty MySQLとの連携方法1のちょっと改造した場合
appendからassignにSmartyの呼び出し方法を変更しましたが、結果はそれほど変わらず、Smartyの場合、Smarty文法の方が優先されるようだ。
ちょっと改造した方法
require_once( 'MySmarty.class.php');
$objSmarty =& new MySmarty;
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
$i=0;
while ($item = mysql_fetch_array($rs)) {
$arg[]=array(
'id'=>$item['id'],
'name'=>$item['name'],
'cell'=>$item['tel'],
'email'=>$item['email'],
);
}
mysql_close($cn);
$objSmarty->assign('contacts', $arg);
$objSmarty->display('hoge1.tmpl');
Smarty MySQLとの連携方法1
Smarty MySQLとの連携方法2
ちょっと改造した方法
require_once( 'MySmarty.class.php');
$objSmarty =& new MySmarty;
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
$i=0;
while ($item = mysql_fetch_array($rs)) {
$arg[]=array(
'id'=>$item['id'],
'name'=>$item['name'],
'cell'=>$item['tel'],
'email'=>$item['email'],
);
}
mysql_close($cn);
$objSmarty->assign('contacts', $arg);
$objSmarty->display('hoge1.tmpl');
Smarty MySQLとの連携方法1
Smarty MySQLとの連携方法2
PHP-HTML::Templateを使った方法
http://phphtmltemplate.sourceforge.net/のPerlのHTML::Templateライクなテンプレートの方法を紹介します。
1回目のアクセスはSmartyより早いですが、2回目以降はSmartyの方が早いです。あたり前か
--php
include("template.php");
$f1 = "templates/htmlhtml.tmpl";// テンプレートファイル
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
while ($item = mysql_fetch_array($rs)) {
$arg[]=array(
'id'=>$item['id'],
'name'=>$item['name'],
'cell'=>$item['tel'],
'email'=>$item['email'],
);
}
mysql_close($cn);
$options = array("filename"=>$f1, "debug"=>0, "die_on_bad_params"=>0);
$template =& new Template($options);
$template->AddParam('loop', $arg);
$template->EchoOutput();
---html---
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
<TMPL_LOOP NAME="loop">
<p>
<TMPL_VAR NAME="name">
<TMPL_VAR NAME="id">
<TMPL_VAR NAME="cell">
<TMPL_VAR NAME="email">
</p>
</TMPL_LOOP>
</body>
</html>
1回目のアクセスはSmartyより早いですが、2回目以降はSmartyの方が早いです。あたり前か
--php
include("template.php");
$f1 = "templates/htmlhtml.tmpl";// テンプレートファイル
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
while ($item = mysql_fetch_array($rs)) {
$arg[]=array(
'id'=>$item['id'],
'name'=>$item['name'],
'cell'=>$item['tel'],
'email'=>$item['email'],
);
}
mysql_close($cn);
$options = array("filename"=>$f1, "debug"=>0, "die_on_bad_params"=>0);
$template =& new Template($options);
$template->AddParam('loop', $arg);
$template->EchoOutput();
---html---
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
<TMPL_LOOP NAME="loop">
<p>
<TMPL_VAR NAME="name">
<TMPL_VAR NAME="id">
<TMPL_VAR NAME="cell">
<TMPL_VAR NAME="email">
</p>
</TMPL_LOOP>
</body>
</html>
Smarty MySQLとの連携方法2
前回紹介した方法より若干速度が速い。ただしプログラム側にデータベースのカラムを追加する必要がある。
array配列を使用したSmaryのassignのサンプル sectionの場合
---php---
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
$id= array();
$name= array();
$tel= array();
$email= array();
while ($item = mysql_fetch_array($rs)) {
array_push($id,$item['id']);
array_push($name,$item['name']);
array_push($tel,$item['tel']);
array_push($email,$item['email']);
}
$objSmarty->assign('id',$id);
$objSmarty->assign('name',$name);
$objSmarty->assign('tel',$tel);
$objSmarty->assign('email',$email);
mysql_close($cn);
$objSmarty->display('html.tmpl');
---html----
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
{section name=customer loop=$id}
<p>
name: {$name[customer]}<br />
id: {$id[customer]}<br />
cell: {$tel[customer]}<br />
e-mail: {$mail[customer]}
</p>
{/section}
</body>
</html>
array配列を使用したSmaryのassignのサンプル sectionの場合
---php---
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
$id= array();
$name= array();
$tel= array();
$email= array();
while ($item = mysql_fetch_array($rs)) {
array_push($id,$item['id']);
array_push($name,$item['name']);
array_push($tel,$item['tel']);
array_push($email,$item['email']);
}
$objSmarty->assign('id',$id);
$objSmarty->assign('name',$name);
$objSmarty->assign('tel',$tel);
$objSmarty->assign('email',$email);
mysql_close($cn);
$objSmarty->display('html.tmpl');
---html----
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
{section name=customer loop=$id}
<p>
name: {$name[customer]}<br />
id: {$id[customer]}<br />
cell: {$tel[customer]}<br />
e-mail: {$mail[customer]}
</p>
{/section}
</body>
</html>
Smarty MySQLとの連携方法1
この方法のメリットはデータベースのカラム名はテンプレートのみに記述するのでプログラム管理が簡単になる。ただし、後から紹介する方法の方が速度は若干速い。
--PHP部分--
require_once( 'MySmarty.class.php');
$objSmarty =& new MySmarty;
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
while ($item = mysql_fetch_array($rs)) {
$objSmarty->append('contacts',$item);
}
mysql_close($cn);
$objSmarty->display('hoge1.tmpl');
---hoge1.tmpl---
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
{section name=customer loop=$contacts}
<p>
name: {$contacts[customer].name}
id: {$contacts[customer].id}
cell: {$contacts[customer].tel}
e-mail: {$contacts[customer].email}
</p>
{/section}
</body>
</html>
--PHP部分--
require_once( 'MySmarty.class.php');
$objSmarty =& new MySmarty;
if (!($cn = mysql_connect("localhost", "hoge", "hoge"))) {
die;
}
if (!(mysql_select_db("test"))) {
die;
}
$sql = "select * from address";
if (!($rs = mysql_query($sql))) {
die;
}
while ($item = mysql_fetch_array($rs)) {
$objSmarty->append('contacts',$item);
}
mysql_close($cn);
$objSmarty->display('hoge1.tmpl');
---hoge1.tmpl---
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>テンプレート</title>
</head>
<body>
<hr />
{section name=customer loop=$contacts}
<p>
name: {$contacts[customer].name}
id: {$contacts[customer].id}
cell: {$contacts[customer].tel}
e-mail: {$contacts[customer].email}
</p>
{/section}
</body>
</html>
Smarty 独自ファイルクラス化
PHP5.0/7.Smartyを使う
HTMLファイルの変更がすぐに反映されないので以下を追加
<:?php
require('Smarty/Smarty.class.php');
class MySmarty extends Smarty {
function MySmarty () {
$this->Smarty();
$this->compile_check = true; // << ここを追加
$mydir = dirname(__FILE__);
$this->template_dir = "$mydir/templates/";
$this->compile_dir = "$mydir/templates_c/";
$this->config_dir = "$mydir/configs/";
$this->cache_dir = "$mydir/cache/";
$this->caching = 0;
}
}
?>
HTMLファイルの変更がすぐに反映されないので以下を追加
<:?php
require('Smarty/Smarty.class.php');
class MySmarty extends Smarty {
function MySmarty () {
$this->Smarty();
$this->compile_check = true; // << ここを追加
$mydir = dirname(__FILE__);
$this->template_dir = "$mydir/templates/";
$this->compile_dir = "$mydir/templates_c/";
$this->config_dir = "$mydir/configs/";
$this->cache_dir = "$mydir/cache/";
$this->caching = 0;
}
}
?>
Wednesday, May 09, 2007
apache2 mod_rewriteを後から追加(インストール)
PHPをインストール済みの場合、あとからapacheを再インストールは大変です。
*DSOでインストールされているか?を確認。されていればOK。
/usr/local/apache2/bin/httpd -lを実行
Compiled-in modules:
http_core.c
mod_so.c これがあれば makeをしないで追加できる
*mod_rewriteをインストール
ソースをDLした場所(例)に
/home//source/httpd-2.2./modules/mappers/mod_rewrite.c
があるか確認
cd /home//source/httpd-2.2./modules/mappers/
$ /usr/local/apache2/bin/apxs -i -a -c ./mod_rewrite.c
apacheの再起動で有効
*DSOでインストールされているか?を確認。されていればOK。
/usr/local/apache2/bin/httpd -lを実行
Compiled-in modules:
http_core.c
mod_so.c これがあれば makeをしないで追加できる
*mod_rewriteをインストール
ソースをDLした場所(例)に
/home//source/httpd-2.2./modules/mappers/mod_rewrite.c
があるか確認
cd /home//source/httpd-2.2./modules/mappers/
$ /usr/local/apache2/bin/apxs -i -a -c ./mod_rewrite.c
apacheの再起動で有効
Tuesday, May 08, 2007
smarty install by Pear
pear upgrade PEAR
pear channel-discover pearified.com
pear install pearified/Smarty
vi /usr/local/lib/php.ini
include_path = ".:/usr/local/lib/php:/usr/local/lib/php/Pearified"
/usr/local/apache2/bin/apachectl stop
/usr/local/apache2/bin/apachectl start
pear channel-discover pearified.com
pear install pearified/Smarty
vi /usr/local/lib/php.ini
include_path = ".:/usr/local/lib/php:/usr/local/lib/php/Pearified"
/usr/local/apache2/bin/apachectl stop
/usr/local/apache2/bin/apachectl start
Sunday, April 22, 2007
Javascript クラス 継承の例
<script type=text/javascript>
<!--
function Team(name,members){
this.name = name;
this.members = members;
}
Team.prototype.add = function(members){
this.members += members;
};
function TeamAAA (name,members) {
this.name = name;
this.members = members;
}
TeamAAA.prototype = new Team();
TeamAAA.prototype.leave = function(members){
this.members -= members;
};
baseball = new TeamAAA("2軍",11);
baseball.leave(3);
document.write("Team name:"+ baseball.name + ", members:"+baseball.members);
//-->
</script>
JavaScript継承パターンまとめ
<!--
function Team(name,members){
this.name = name;
this.members = members;
}
Team.prototype.add = function(members){
this.members += members;
};
function TeamAAA (name,members) {
this.name = name;
this.members = members;
}
TeamAAA.prototype = new Team();
TeamAAA.prototype.leave = function(members){
this.members -= members;
};
baseball = new TeamAAA("2軍",11);
baseball.leave(3);
document.write("Team name:"+ baseball.name + ", members:"+baseball.members);
//-->
</script>
JavaScript継承パターンまとめ
Javascript クラス コンストラクトの例
<script type=text/javascript>
<!--
function Team(name,members){
this.name = name;
this.members = members;
}
Team.prototype.add = function(members){
this.members += members;
};
football = new Team("Japan",11);
football.add(3);
document.write("Team name:"+ football.name + ", members:"+football.members);
//-->
</script>
<!--
function Team(name,members){
this.name = name;
this.members = members;
}
Team.prototype.add = function(members){
this.members += members;
};
football = new Team("Japan",11);
football.add(3);
document.write("Team name:"+ football.name + ", members:"+football.members);
//-->
</script>
Friday, April 20, 2007
Javascript 多次元配列のソートの例
<script type=text/javascript>
<!--
function sort1(a,b){ return a[1] - b[1] }
function sort2(a,b){ return a[2] - b[2] }
xx = new Array(3, 7, 8, 1);
xx.sort();
document.write(xx);
document.write("<br>");
var persons =
[
[ 'Tanaka' , '32' ,'Japan'] ,
[ 'John' , '38' ,'UK'] ,
[ 'Ken' , '26' ,'France'] ,
[ 'John' , '49' ,'India'] ,
]
persons.sort();
for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
document.write("<br>");
persons.sort(sort1)
for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
document.write("<br>");
persons.sort(sort2)
for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
//-->
</script>
意外と遅いらしい。
<!--
function sort1(a,b){ return a[1] - b[1] }
function sort2(a,b){ return a[2] - b[2] }
xx = new Array(3, 7, 8, 1);
xx.sort();
document.write(xx);
document.write("<br>");
var persons =
[
[ 'Tanaka' , '32' ,'Japan'] ,
[ 'John' , '38' ,'UK'] ,
[ 'Ken' , '26' ,'France'] ,
[ 'John' , '49' ,'India'] ,
]
persons.sort();
for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
document.write("<br>");
persons.sort(sort1)
for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
document.write("<br>");
persons.sort(sort2)
for (var i = 0; i < persons.length; i ++) {
document.write(persons[i] + "<br>");
}
//-->
</script>
意外と遅いらしい。
Thursday, April 19, 2007
Date Javascript
var date = new Date ();
date.setTime(1);
mdate = date.getFullYear() +"/" + (date.getMonth()+1) + "/" + date.getDate();
alert(mdate );
date.getDay // 0から始まる曜日を返す。0は日曜日、6が土曜日
date.setTime(1);
mdate = date.getFullYear() +"/" + (date.getMonth()+1) + "/" + date.getDate();
alert(mdate );
date.getDay // 0から始まる曜日を返す。0は日曜日、6が土曜日
Wednesday, April 18, 2007
無名配列 Anonymous Arrayの例 Javascript
var persons = [
{ Name: "田中", Age: 20 },
{ Name: "山田", Age: 18 },
{ Name: "青木", Age: 15 }
];
for (var i = 0; i < persons.length; i ++) {
alert(persons[i].Name + ":" +persons[i].Age);
}
{ Name: "田中", Age: 20 },
{ Name: "山田", Age: 18 },
{ Name: "青木", Age: 15 }
];
for (var i = 0; i < persons.length; i ++) {
alert(persons[i].Name + ":" +persons[i].Age);
}
連想配列のサンプル JavaScript
連想配列のサンプル
person1 = new Array();
person1["Name"] = "Mike";
document.write(person1["Name"] );
person1 = new Array();
person1["Name"] = "Mike";
document.write(person1["Name"] );
Thursday, April 12, 2007
Wednesday, April 11, 2007
Tuesday, April 10, 2007
Exporter
package Constant;
use strict;
BEGIN{
use Exporter;
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
@ISA = qw(Exporter);
@EXPORT = qw(
HOGE
HOGE2
);
%EXPORT_TAGS = ();
@EXPORT_OK = ();
}
use constant HOGE => 'hoge';
use constant HOGE2 => 2;
1
~
-----
#!/usr/local/bin/perl
use Constant;
print HOGE2;
use strict;
BEGIN{
use Exporter;
use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
@ISA = qw(Exporter);
@EXPORT = qw(
HOGE
HOGE2
);
%EXPORT_TAGS = ();
@EXPORT_OK = ();
}
use constant HOGE => 'hoge';
use constant HOGE2 => 2;
1
~
-----
#!/usr/local/bin/perl
use Constant;
print HOGE2;
ENDサブルーチン Perl
exitやdieで終了したあとで呼ばれる。
ただし「exec」、「kill -9」または異常終了などがあると呼ばれない。
複数ある場合は文の最後から呼ばれる。
exit;
END{
print "end1\n";
}
END{
print "end2\n";
}
END{
print "end3\n";
}
----- 結果 ----
end3
end2
end1
となる
ただし「exec」、「kill -9」または異常終了などがあると呼ばれない。
複数ある場合は文の最後から呼ばれる。
exit;
END{
print "end1\n";
}
END{
print "end2\n";
}
END{
print "end3\n";
}
----- 結果 ----
end3
end2
end1
となる
日付関係
use POSIX 'strftime';
print strftime ("%Y/%m/%d %H:%M:%S", localtime);
参考URL
http://blog.livedoor.jp/dankogai/archives/50180654.html
http://www2u.biglobe.ne.jp/~MAS/perl/waza/strftime.html
print strftime ("%Y/%m/%d %H:%M:%S", localtime);
参考URL
http://blog.livedoor.jp/dankogai/archives/50180654.html
http://www2u.biglobe.ne.jp/~MAS/perl/waza/strftime.html
Friday, April 06, 2007
ダウンロードコンテンツの著作権関連のサンプル
Content-Type: application/vnd.oma.dd+xml
Content-length: 50
image/jpg
http://myserver/dl.cgi?img=picture.jpg
1234
著作権関連のOMAのサンプル
Content-length: 50
著作権関連のOMAのサンプル
ファイルサイズを求める -s
perlでのサンプル
my $body;
open(MP3, $file) || die("can't open \n $!");
read(MP3, $body, -s $file);
close(MP3);
print $body;
my $body;
open(MP3, $file) || die("can't open \n $!");
read(MP3, $body, -s $file);
close(MP3);
print $body;
正規表現の例 perl
my $n = 5;
unless ($n =~ /^[1-5]$/) {
print "n is not from one to five";
}else{
print "n is between one and five";
}
unless ($n =~ /^[1-5]$/) {
print "n is not from one to five";
}else{
print "n is between one and five";
}
Yahoo!ケイタイの動画、転送不可のHTTPヘッダのサンプル
Yahoo!ケイタイの動画、転送不可のHTTPヘッダのサンプル
Content-type: video/3gpp\nContent-length: 100\nx-jphone-copyright: no-store\n\n
サイズ Content-lengthは
-s で求めたりする。
http://developers.softbankmobile.co.jp/dp/tool_dl/web/tech.php
を参照。
Content-type: video/3gpp\nContent-length: 100\nx-jphone-copyright: no-store\n\n
サイズ Content-lengthは
-s で求めたりする。
http://developers.softbankmobile.co.jp/dp/tool_dl/web/tech.php
を参照。
Thursday, April 05, 2007
Perl テストプランツールのサンプル
テストプランツールのサンプル
#!/usr/local/bin/perl -w
use strict;
use Data::Dumper;
use Test::More qw(no_plan);
use lib './lib';
BEGIN {
use_ok('Original::Person');# パールモジュール
};
my $p = Original::Person->new('Tom');
is ($p->tel,'0123-123-1234', 'tel number');
is ($p->age,'24', 'age');
#!/usr/local/bin/perl -w
use strict;
use Data::Dumper;
use Test::More qw(no_plan);
use lib './lib';
BEGIN {
use_ok('Original::Person');# パールモジュール
};
my $p = Original::Person->new('Tom');
is ($p->tel,'0123-123-1234', 'tel number');
is ($p->age,'24', 'age');
prototype.js を使ったチャットシステムの習作
ログファイルのロックやサイズ制限などは入れていないです。
単純にprototype.js の練習用です。
<html>
<head>
<script type="text/javascript" src="./js/prototype-1.5.0.js"></script>
<script type="text/javascript">
//<![CDATA[
function updateResult(req){
$("status").innerHTML = req.responseText ;
}
function update() {
var url = './read.pl';
var params = '';
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params,
onComplete: updateResult
});
}
function execute() {
var url = './write.pl';
var params = Form.serialize($('form1'));
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params
});
}
function adListener() {
periodicalExecuter = new PeriodicalExecuter(update, 1);
}
//]]>
</script>
</head>
<body onload="adListener()">
<form id="form1" onSubmit="execute()">
message <input type="text" name="message" id="d_message" value=""><br>
<input type="submit" value="entry">
</form>
<hr>
<span id="status"></span>
</body>
</html>
-----write.pl
#!/usr/bin/perl -w
# モジュール読み込み
use strict;
use CGI;
print 'Content-Type: text/html', "\n\n";
#オブジェクト作成
my $q = CGI->new;
my $message = $q->param('message');
if ($message){
# ファイルロック処理は入れていない
open(OUTFILE, ">> /tmp/mes.txt");
print OUTFILE $message."\n";
close OUTFILE;
print $message;
}
----read.pl----
#!/usr/bin/perl -w
# モジュール読み込み
use strict;
print 'Content-Type: text/html', "\n\n";
my $file = '/tmp/mes.txt';
if ( -e $file) {
open( READ, $file );
my @lines = <READ>;
close( READ );
my $num = @lines;
my @lists = @lines[$num-5 .. $num-1];# 最後からデータを取得
foreach (@lists) {
print $_,"<br>";
}
}
単純にprototype.js の練習用です。
<html>
<head>
<script type="text/javascript" src="./js/prototype-1.5.0.js"></script>
<script type="text/javascript">
//<![CDATA[
function updateResult(req){
$("status").innerHTML = req.responseText ;
}
function update() {
var url = './read.pl';
var params = '';
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params,
onComplete: updateResult
});
}
function execute() {
var url = './write.pl';
var params = Form.serialize($('form1'));
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params
});
}
function adListener() {
periodicalExecuter = new PeriodicalExecuter(update, 1);
}
//]]>
</script>
</head>
<body onload="adListener()">
<form id="form1" onSubmit="execute()">
message <input type="text" name="message" id="d_message" value=""><br>
<input type="submit" value="entry">
</form>
<hr>
<span id="status"></span>
</body>
</html>
-----write.pl
#!/usr/bin/perl -w
# モジュール読み込み
use strict;
use CGI;
print 'Content-Type: text/html', "\n\n";
#オブジェクト作成
my $q = CGI->new;
my $message = $q->param('message');
if ($message){
# ファイルロック処理は入れていない
open(OUTFILE, ">> /tmp/mes.txt");
print OUTFILE $message."\n";
close OUTFILE;
print $message;
}
----read.pl----
#!/usr/bin/perl -w
# モジュール読み込み
use strict;
print 'Content-Type: text/html', "\n\n";
my $file = '/tmp/mes.txt';
if ( -e $file) {
open( READ, $file );
my @lines = <READ>;
close( READ );
my $num = @lines;
my @lists = @lines[$num-5 .. $num-1];# 最後からデータを取得
foreach (@lists) {
print $_,"<br>";
}
}
Wednesday, April 04, 2007
prototype.js のサンプル
----time.pl----
#!/usr/bin/perl
use strict;
print 'Content-Type: text/html', "\n\n";
my ($ss, $mn, $hh, $dd, $mm, $yy) = localtime(time);
$yy += 1900;
$mm++;
my $my_time = sprintf("%04d.%02d.%02d %02d:%02d:%02d", $yy, $mm, $dd, $hh, $mn, $ss);
print $my_time;
---end---
<html>
<head>
<script type="text/javascript" src="./js/prototype-1.5.0.js"></script>
<script type="text/javascript">
//<![CDATA[
function updateResult(req){
$("status").innerHTML = req.responseText ;
}
function update() {
var url = './time.pl';
var params = 'c=time';// つかわないが。。
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params,
onComplete: updateResult
});
}
function adListener() {
periodicalExecuter = new PeriodicalExecuter(update, 1);
}
//]]>
</script>
</head>
<body onload="adListener()">
time :
<span id="status"></span>
</body>
</html>
#!/usr/bin/perl
use strict;
print 'Content-Type: text/html', "\n\n";
my ($ss, $mn, $hh, $dd, $mm, $yy) = localtime(time);
$yy += 1900;
$mm++;
my $my_time = sprintf("%04d.%02d.%02d %02d:%02d:%02d", $yy, $mm, $dd, $hh, $mn, $ss);
print $my_time;
---end---
<html>
<head>
<script type="text/javascript" src="./js/prototype-1.5.0.js"></script>
<script type="text/javascript">
//<![CDATA[
function updateResult(req){
$("status").innerHTML = req.responseText ;
}
function update() {
var url = './time.pl';
var params = 'c=time';// つかわないが。。
var ajax = new Ajax.Request(url, { method: 'post',
parameters: params,
onComplete: updateResult
});
}
function adListener() {
periodicalExecuter = new PeriodicalExecuter(update, 1);
}
//]]>
</script>
</head>
<body onload="adListener()">
time :
<span id="status"></span>
</body>
</html>
Tuesday, April 03, 2007
Perl CGIスクリプトをコマンドラインから実行する
ブラウザでしか確認できないということをよく聞く。コマンドラインから実行した方がはるかに簡単にデバッグできる。
----test.cgi-----
#!/usr/local/bin/perl
use strict;
use CGI;
print "Content-type: text/html;charset=Shift_JIS\n\n";
my $q = new CGI;
my $name = $q->param('name');
my $id = $q->param('id');
print $name,"\n";
print $id,"\n";
以下のような場合
./test.cgi name='moji' id=2 と実行すればよい。
----test.cgi-----
#!/usr/local/bin/perl
use strict;
use CGI;
print "Content-type: text/html;charset=Shift_JIS\n\n";
my $q = new CGI;
my $name = $q->param('name');
my $id = $q->param('id');
print $name,"\n";
print $id,"\n";
以下のような場合
./test.cgi name='moji' id=2 と実行すればよい。
Friday, March 30, 2007
MVCの練習 perl
---index.cgi-----
#!/usr/local/bin/perl
use strict;
use Controller;
Controller->new->dispatch('index');# Sledge風にしてみました。
----Controller.pm -----
package Controller;
use strict;
use CGI;
use Model;
use View;
use Error qw(:try);
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
}
sub dispatch {
my $self = shift;
my $page = shift||'index';
print "Content-Type: text/html;\n\n";
try {
my $q = new CGI;
my $color = $q->param('color')||'white';
my $model = new Model($color);
my $view = new View;
if ($model->get_RGB){
$view->hit_page($page,$model->get_RGB);
}else{
$view->not_found_page($page);
}
}catch Error with {
my $e = shift;
warn "system error: " . $e->text;
} finally {
;
}
}
1;
----Modal.pm-----
package Model;
use strict;
sub new {
my $class = shift;
my $self = {};
$self->{color} = shift;
bless $self, $class;
}
sub get_RGB {
my $self = shift;
if ($self->{color} eq "white"){
return "#FFFFFF";
}else{
return "";
}
}
1;
----View.pm------
package View;
use strict;
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
}
sub not_found_page {
my ($self, $str) = @_;
print $str,"not found\n"
}
sub hit_page{
my ($self, $page,$str) = @_;
my $out = sprintf("page :%s, str :%s\n",$page,$str);
print $out;
}
1;
---
#!/usr/local/bin/perl
use strict;
use Controller;
Controller->new->dispatch('index');# Sledge風にしてみました。
----Controller.pm -----
package Controller;
use strict;
use CGI;
use Model;
use View;
use Error qw(:try);
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
}
sub dispatch {
my $self = shift;
my $page = shift||'index';
print "Content-Type: text/html;\n\n";
try {
my $q = new CGI;
my $color = $q->param('color')||'white';
my $model = new Model($color);
my $view = new View;
if ($model->get_RGB){
$view->hit_page($page,$model->get_RGB);
}else{
$view->not_found_page($page);
}
}catch Error with {
my $e = shift;
warn "system error: " . $e->text;
} finally {
;
}
}
1;
----Modal.pm-----
package Model;
use strict;
sub new {
my $class = shift;
my $self = {};
$self->{color} = shift;
bless $self, $class;
}
sub get_RGB {
my $self = shift;
if ($self->{color} eq "white"){
return "#FFFFFF";
}else{
return "";
}
}
1;
----View.pm------
package View;
use strict;
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
}
sub not_found_page {
my ($self, $str) = @_;
print $str,"not found\n"
}
sub hit_page{
my ($self, $page,$str) = @_;
my $out = sprintf("page :%s, str :%s\n",$page,$str);
print $out;
}
1;
---
Thursday, March 29, 2007
apache の設定サンプル
<Files *.pl>
Options ExecCGI
allow from all
SetHandler perl-script
PerlHandler Apache::Registry
PerlModule Apache::DBI
PerlInitHandler Apache::StatINC
PerlSendHeader Off
PerlSetEnv TMPDIR /tmp
</Files>
Options ExecCGI
allow from all
SetHandler perl-script
PerlHandler Apache::Registry
PerlModule Apache::DBI
PerlInitHandler Apache::StatINC
PerlSendHeader Off
PerlSetEnv TMPDIR /tmp
</Files>
Template Toolkit CGI.pmの例
use strict;
use Template;
use CGI;
my $q = CGI->new;
print "Content-type: text/html\n\n";
my $output;
my $template = Template->new({
OUTPUT => \$output,
TRIM =>1,
});
$template->process(
'fillin.html',
{
apr =>$q,
},
) or print $template->error;
print $output;
-----
[% USE FillInForm %]
[% FILTER fillinform fobject => apr %]
<!-- this form becomes sticky -->
<form action="foo" method="POST">
<input type="text" name="foo">
<input value="" type="hidden" name="bar">
<input value="foo" type="radio" checked name="baz">
<input value="bar" type="radio" name="baz">
</form>
[% END %]
use Template;
use CGI;
my $q = CGI->new;
print "Content-type: text/html\n\n";
my $output;
my $template = Template->new({
OUTPUT => \$output,
TRIM =>1,
});
$template->process(
'fillin.html',
{
apr =>$q,
},
) or print $template->error;
print $output;
-----
[% USE FillInForm %]
[% FILTER fillinform fobject => apr %]
<!-- this form becomes sticky -->
<form action="foo" method="POST">
<input type="text" name="foo">
<input value="" type="hidden" name="bar">
<input value="foo" type="radio" checked name="baz">
<input value="bar" type="radio" name="baz">
</form>
[% END %]
Tuesday, March 27, 2007
パラメータの値をそのまま Template Toolkit
#!/usr/local/bin/perl
use strict;
use Template;
use CGI;
my $q = CGI->new;
print "Content-type: text/html\n\n";
my $output;
my $template = Template->new({
OUTPUT => \$output,
TRIM =>1,
});
$template->process(
'sample2.html',
{ cgi =>$q,
},
) or print $template->error;
print $output;
$q->param("money","dollar");
-----template---
[% cgi.param('money') %]
use strict;
use Template;
use CGI;
my $q = CGI->new;
print "Content-type: text/html\n\n";
my $output;
my $template = Template->new({
OUTPUT => \$output,
TRIM =>1,
});
$template->process(
'sample2.html',
{ cgi =>$q,
},
) or print $template->error;
print $output;
$q->param("money","dollar");
-----template---
[% cgi.param('money') %]
ハッシュからURLパラメータ perl
my %hash = ();
$hash{test} = 1;
$hash{test2} = 21;
$hash{test3} = 31;
my $parameter = join '&', map {"$_=$hash{$_}"} keys %hash;
print $parameter; # test2=21&test3=31&test=1
$hash{test} = 1;
$hash{test2} = 21;
$hash{test3} = 31;
my $parameter = join '&', map {"$_=$hash{$_}"} keys %hash;
print $parameter; # test2=21&test3=31&test=1
Perl データベースへのアクセスのサンプル
最近ではDBIx::Class や Class::DBIでデータベースをアクセスすることが多く。直接SQLを書くこともすくなくなりましたが、基本のサンプルを書いておきます。
そのままでは動きません。
my $dbh=DBI->connect(DBI,{PrintError=>0,AutoCommit=>1}) or die ;
my $sql=qq[SELECT id ,name FROM user WHERE age=? AND area=?];#プレースホルダを使用
@bind=(17,14);
$sth = $dbh->prepare($sql)|| die $dbh->errstr;
$sth->execute(@bind);
if ($sth->errstr ne ""){ # DBエラー
#エラー処理
}
while( ( $login_id, $login_name ) = $sth->fetchrow_array() ) {
}
$sth->finish;
$dbh->disconnect;
そのままでは動きません。
my $dbh=DBI->connect(DBI,{PrintError=>0,AutoCommit=>1}) or die ;
my $sql=qq[SELECT id ,name FROM user WHERE age=? AND area=?];#プレースホルダを使用
@bind=(17,14);
$sth = $dbh->prepare($sql)|| die $dbh->errstr;
$sth->execute(@bind);
if ($sth->errstr ne ""){ # DBエラー
#エラー処理
}
while( ( $login_id, $login_name ) = $sth->fetchrow_array() ) {
}
$sth->finish;
$dbh->disconnect;
abstract サンプル Perl アブストラクトメソッド
親クラスで定義したメソッドを呼ばず、子クラスでのメソッドが呼ばれます。
---Foo.pm-----
package Foo;
sub new{
my $pkg = shift;
my $hash= {};
bless $hash,$pkg;
}
sub sub1{
my $self = shift;
$self->sub2;
}
sub sub2{
my $self = shift;
print "this is abstract\n";
}
1;
---Foo2.pm (Fooの子クラス)-----
package Foo2;
use base qw(Foo);
sub sub2{
my $self = shift;
print "Foo2 sub2\n";
}
1;
--- main.pl (実行スクリプト)---
#!/usr/local/bin/perl
use Foo2;
my $f = Foo2->new;
$f->sub1;
__END__
--- 実行結果
Foo2 sub2
---Foo.pm-----
package Foo;
sub new{
my $pkg = shift;
my $hash= {};
bless $hash,$pkg;
}
sub sub1{
my $self = shift;
$self->sub2;
}
sub sub2{
my $self = shift;
print "this is abstract\n";
}
1;
---Foo2.pm (Fooの子クラス)-----
package Foo2;
use base qw(Foo);
sub sub2{
my $self = shift;
print "Foo2 sub2\n";
}
1;
--- main.pl (実行スクリプト)---
#!/usr/local/bin/perl
use Foo2;
my $f = Foo2->new;
$f->sub1;
__END__
--- 実行結果
Foo2 sub2
ハッシュに関数を入れてみる perl
携帯向けサイトなどで使えそうな感じですね。
my %controller = (
i => \&i_page,
e => \&e_page,
y => \&y_page,
);
my $ca = "i";
$controller{$ca}->("iii") if $ca eq "i";
$controller{$ca}->("eee","test2")if $ca eq "e";
$controller{$ca}->("yyy") if $ca eq "y";
sub i_page{
my $str = shift;
print $str;
}
sub e_page{
my ($str,$str2) = @_;
print $str,$str2;
}
sub y_page{
my $str = shift;
print $str;
}
my %controller = (
i => \&i_page,
e => \&e_page,
y => \&y_page,
);
my $ca = "i";
$controller{$ca}->("iii") if $ca eq "i";
$controller{$ca}->("eee","test2")if $ca eq "e";
$controller{$ca}->("yyy") if $ca eq "y";
sub i_page{
my $str = shift;
print $str;
}
sub e_page{
my ($str,$str2) = @_;
print $str,$str2;
}
sub y_page{
my $str = shift;
print $str;
}
時間の比較 Time::PieceとDate::Calc perl
use Time::Piece;
use Date::Calc qw(Delta_DHMS);
my $start = localtime;
sleep 3;
my $end = localtime;
my $diff = $end - $start;
# my $diff = $start - $end;
print $diff,"\n";
my @df =Delta_DHMS($start->year,$start->mon,$start->mday,$start->hour,$start->min,$start->sec,
$end->year,$end->mon,$end->mday,$end->hour,$end->min,$end->sec);
$" = ',';# カンマ区切りで出力
print "@df\n";
use Date::Calc qw(Delta_DHMS);
my $start = localtime;
sleep 3;
my $end = localtime;
my $diff = $end - $start;
# my $diff = $start - $end;
print $diff,"\n";
my @df =Delta_DHMS($start->year,$start->mon,$start->mday,$start->hour,$start->min,$start->sec,
$end->year,$end->mon,$end->mday,$end->hour,$end->min,$end->sec);
$" = ',';# カンマ区切りで出力
print "@df\n";
Sunday, March 25, 2007
Perl でPHPのようにリンクに自動的にセッションパラメータを付ける
HTML::StickyQueryをつかえば可能です。
ただしPHPではFormにも自動的にhiddentタグでセッションを渡すことができますが、
この部分は手動で行う必要があります。
ただしPHPではFormにも自動的にhiddentタグでセッションを渡すことができますが、
この部分は手動で行う必要があります。
タイムアウトをさせない
$|=1;#バッファリング制御
my $interval = 10;
eval {
local $SIG{ALRM} = sub { # ALRM シグナルをキャッチした
print "\n";
alarm $interval;
};
alarm $interval;
# 重たい処理をここでする
sleep 10;
};
alarm 0;
if ($@) {
die "$@";
}
$|=0;#バッファリング制御 元に戻す
my $interval = 10;
eval {
local $SIG{ALRM} = sub { # ALRM シグナルをキャッチした
print "\n";
alarm $interval;
};
alarm $interval;
# 重たい処理をここでする
sleep 10;
};
alarm 0;
if ($@) {
die "$@";
}
$|=0;#バッファリング制御 元に戻す
指定の配列のランダム
my @id =(0,1,2,3,4,5,6,7,8,9);
my @ret;
for (1..@id) {
push @ret, splice(@id, int(rand(@id)), 1);
}
print @ret;
my @ret;
for (1..@id) {
push @ret, splice(@id, int(rand(@id)), 1);
}
print @ret;
クラスとメソッドを一度に呼ぶサンプル Perl
---- Game.pm ------
package Game;
use strict;
use Carp qw(croak);
sub new{
my $class = shift;
my $name = shift || croak ('set name');
bless{
name => $name,
},$class;
}
sub name{
my $self = shift;
$self->{name};
}
1;
__END__
---- Player.pm -----
package Player;
use strict;
use Carp qw(croak);
use Game;
sub new{
my $class = shift;
my $self = {};
bless $self, $class;
}
sub run{
my $self = shift;
print $self->game->name;
}
sub game{
my $self = shift;
unless (defined $self->{game}){
$self->{game}= Game->new('race');
}
return $self->{game};
}
1;
__END__
---- index.cgi------
#!/usr/bin/perl
use Player;
use strict;
Player->new->run;
package Game;
use strict;
use Carp qw(croak);
sub new{
my $class = shift;
my $name = shift || croak ('set name');
bless{
name => $name,
},$class;
}
sub name{
my $self = shift;
$self->{name};
}
1;
__END__
---- Player.pm -----
package Player;
use strict;
use Carp qw(croak);
use Game;
sub new{
my $class = shift;
my $self = {};
bless $self, $class;
}
sub run{
my $self = shift;
print $self->game->name;
}
sub game{
my $self = shift;
unless (defined $self->{game}){
$self->{game}= Game->new('race');
}
return $self->{game};
}
1;
__END__
---- index.cgi------
#!/usr/bin/perl
use Player;
use strict;
Player->new->run;
Friday, March 23, 2007
Javascript 選択文字の取得
function getText()
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
document.getElementById("msg").innerHTML = txt;
}
{
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (document.getSelection)
{
txt = document.getSelection();
}
else if (document.selection)
{
txt = document.selection.createRange().text;
}
else return;
document.getElementById("msg").innerHTML = txt;
}
Thursday, March 22, 2007
Ajaxを使わない 処理中の表示
#!/usr/bin/perl
use strict;
$=1;#バッファリング制御
print 'Content-Type: text/html', "\n\n";
my $html = <<__HTML__;
<html>
<head>
</head>
<body>
<img src="./img/indicator_remembermilk_orange.gif"> <-- 処理中をあらわす画像-->
</body>
</html>
__HTML__
print $html;
sleep 10;# 重い(長い)処理
$=0;#バッファリング制御
my $js = <<__JAVASCRIPT__;
<script language="JavaScript">
<!--location.href='test.html'// -->
</script>
__JAVASCRIPT__
print $js;
__END__
use strict;
$=1;#バッファリング制御
print 'Content-Type: text/html', "\n\n";
my $html = <<__HTML__;
<html>
<head>
</head>
<body>
<img src="./img/indicator_remembermilk_orange.gif"> <-- 処理中をあらわす画像-->
</body>
</html>
__HTML__
print $html;
sleep 10;# 重い(長い)処理
$=0;#バッファリング制御
my $js = <<__JAVASCRIPT__;
<script language="JavaScript">
<!--location.href='test.html'// -->
</script>
__JAVASCRIPT__
print $js;
__END__
無名ハッシュを配列で管理
my $ref_steps = &get_steps();
# 配列をデリファレンス @$ref_steps -->@{$ref_steps}
foreach my $sp (@$ref_steps) {
print sprintf("%s file %d 行\n", $sp->{file},$sp->{steps});
}
sub get_steps{
my @list; my $i=1;
for my $key ( qw(hoge hoge2 hoge3) ) {
push (@list, { file=>$key,steps=>$i });
$i++;
}
return \@list;
}
# 配列をデリファレンス @$ref_steps -->@{$ref_steps}
foreach my $sp (@$ref_steps) {
print sprintf("%s file %d 行\n", $sp->{file},$sp->{steps});
}
sub get_steps{
my @list; my $i=1;
for my $key ( qw(hoge hoge2 hoge3) ) {
push (@list, { file=>$key,steps=>$i });
$i++;
}
return \@list;
}
Subscribe to:
Posts (Atom)