|
Perl CGI TIPS
|
![]() |
| #1 配列@dataの要素を順に表示するには? for ($i=0;$i<@data;$i++){ print "$data[$i]\n"; } |
| #2 連想配列$DATA{$key}の要素を順に表示するには? foreach $key (keys %DATA) { print "$key $DATA{$key}\n" } |
while(list($key,$val)=each($DATA)){ print "$key $val\n" } |
| #3 文字列を記号で分割するには? @answer = split(/:/,$data); |
$answer = explode(":", $data); |
| #4 マッチした文字を削除するには? $data = "me and you and"; $data =~ s/and//; |
$data = "me and you and"; $html = ereg_replace("and","",$data); |
| #5 サブルーチンにデータを渡すには? &error($date, $data); sub error{ my($date, $data) = @_; print "$date $data\n"; } |
Error ($date, $data); Function Error($date, $data) { |
| #6 コマンドを実行するには? $look = `ls -al`; print $look; |
$look = system("/bin/ls -al"); print $look; |
|
#7 別のページへジャンプするには? print "Location: http://hogehoge/\n\n"; |
header("Location: http://hogehoge/"); |
|
#8 クッキーを取得するには? @cookies = split(/; /,$ENV{'HTTP_COOKIE'}); foreach (@cookies) { ($key, $value) = split(/=/); print "$key $value\n"; } |
|
#9 日本語の漢字コードを変換するには? require 'jcode.pl'; $name = "漢字"; &jcode'convert(*name,'euc'); |
$name = "漢字"; $name = i18n_convert($name, "EUC-JP", "SJIS"); |
| #10 並びの順番を入れた数字にだぶりがないかチェックするには? for ($i=0;$i<@order;$i++){ for ($j=0;$j<@order;$j++){ if ($j ne $i){ if ($order[$j] eq $order[$i]){&error('順番がだぶってますー!');} } } } |
| #11 中身があるディレクトリを削除するには? use File::Path; $deldir = "myhome"; if( -e $deldir ){ rmtree($deldir); } |
| #12 ファイルを読んで変数に入れるには? $file = "data.txt"; if (-e "$file"){ open (DAT, "$file"); while (<DAT>) { $data .= $_; } close (DAT); } |
$file = "data.txt"; if (file_exists("$file")){ $fd = fopen ("$file", "r"); while (!feof ($fd)) { $data .= fgets($fd, 4096); } fclose ($fd); } |
| #13 ループを抜けるには? while(1) $n++;{ if ($n > 10){last;} } |
while(1) $n++;{ if ($n > 10){break;} } |
| #14 配列の数を数えるには?
$kazu = @data; |
$kazu = count($data); |
| #15 ディレクトリ内ファイルを操作する?
opendir(DIR, "$dir"); |
| #15 数字だけを抜き出すには?
|
$match = preg_match_all ("/([0-9]+)/", $str, $regs); while(list($key,$val)=each($regs[1])){ $result .= $val; } |