perlまとめ
移転しました。
文字列中のURLを自動的にリンクさせたい
$tmp =~ s/(s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/<a href="$1">$1<\/a>/g;
改行文字取り除く
chompで取り除ける改行文字は\rの場合のみなので、\r\nという改行を取り除こうとした場合に、\nが残ってしまって困る。
このため以下ように取り除く。
$string =~ s/\r//; $string =~ s/\n//;
ディレクトリの読み取り
ディレクトリ内のファイルとディレクトリをすべて読み出して表示させる例
参考URL
opendir(DIR, "/home/kent/public_html"); @file = readdir(DIR); closedir(DIR); foreach (@file) { print "$_\n"; }
テキストファイルからHTMLファイルへ変換
需要があるようでググると幾つかでてきた。そのうちのひとつを以下に記載。参考URLそのまま。
参考URL
#!/usr/local/bin/perl #置換えするディレクトリの指定 $dirset = '.'; #変換数カウント用 $countok = 0; $countng = 0; #ディレクトリ内の情報取得 opendir(DIR , $dirset); while($view = readdir(DIR)) { push(@dirlist,$view); } foreach $tmp (@dirlist) { if ($tmp =~ /\.txt$/i) { &puthtml($tmp); } } #完了メッセージを表示する print "Content-type: text/html\n\n"; print "<META http-equiv=\"Content-Type\" content=\"text/html; charset=Shift_JIS\">\n"; print "HTMLファイルへの変換が終了しました。(正常$countok個)<BR>\n"; print "HTMLファイルへの変換が終了しました。(異常$countng個)<BR>\n"; exit; #HTMLファイル書き出しルーチン sub puthtml { my ($fname) = $_[0]; open (IN,$fname); @aaa = <IN>; close (IN); $outfile = <<"HTML"; <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> </HEAD> <BODY> HTML foreach $tmp (@aaa) { $tmp =~ s/\r\n/<BR>\n/; $tmp =~ s/\r/<BR>\n/; $tmp =~ s/\n/<BR>\n/; $outfile .= $tmp; } $outfile .= <<"HTML"; </BODY> </HTML> HTML #書き出すHTMLファイル名を整形する $fname =~ s/\.txt//; $fname = $fname . '.html'; if (open (OUT,">$fname")) { print OUT $outfile; close (OUT); $countok++; } else { $countng++; } }