よく使うPerlスニペット
Perlでアレ、どうやって書くんだっけ?と毎回悩むものの、エディタに設定を組み込む気合いも足りない私は、よく書くアレをどっかからコピペで済ませたい。
そんな、ものぐさ太郎な私のためのメモ書きです。
カレントディレクトリのlibからモジュール読み込みしたい
use FindBin; use lib "$FindBin::Bin/lib";
標準入出力を全部UTF-8にしたい
use strict; use warnings; use utf8; use open IO => qw/:encoding(UTF-8) :std/;
標準入出力を全部Shift_JISにしたい
use strict; use warnings; use utf8; use open IO => qw/:encoding(cp932) :std/;
入出力を個別に(エン|デ)コードしたい
use strict; use warnings; use utf8; use Encode 'encode', 'decode';
標準入出力をまとめて(エン|デ)コードしたい
use strict; use warnings; use utf8; binmode STDIN, ':encoding(cp932)'; binmode STDOUT, ':encoding(cp932)'; binmode STDERR, ':encoding(cp932)';
データをダンプして中身を丸見えにしたい
use Data::Dumper; print Dumper $secret;
MySQLに接続したい
use DBI;
my $database = "DB_NAME";
my $hostname = "localhost";
my $user = "YOUR_USER_NAME";
my $password = "YOUR_PASSWORD";
my $dbh = DBI->connect(
"DBI:mysql:$database:$hostname",
$user,
$password
) or die "cannot connect to MySWL: $DBI::errstr";
$dbh->do("set names utf8");
ハッシュのキーとバリューを展開したい
my %address = (
"上岡" => "愛知県稲沢市",
"山田" => "東京都渋谷区",
);
while (my ($key, $value) = each(%address)){
print "key=$key, value=$value\n";
}
ハッシュのキーを展開したい
my %address = (
"上岡" => "愛知県稲沢市",
"山田" => "東京都渋谷区",
);
foreach my $key(keys(%address)){
print "$address{$key}\n";
}
ファイルを読み込む
sub open_file {
my $filename = shift;
open my $fh, '<', $filename
or die "Couldn't open $read_filename : $!" ; return $fh;
}
ファイルに書き込む
sub write_file {
my ($filename, $contents) = @_;
open my $write, '>>', $filename
or die "Couldn't open : $!";
print {$write} $contents;
close $write;
}