LoginSignup
1
3

More than 5 years have passed since last update.

perlメモ

Last updated at Posted at 2017-05-24

Perl開発で使用している技術のメモ

基本的に業務で使用していることの備忘録として書いているので、技術に偏りがある可能性もあります。細かな説明は少しずつ追記していきます。
メモなので、業務の中で何度も更新します。編集履歴見てもいいことないです。

tinyで設定ファイルを読み込み

use Config::Tiny;
my $conf = Config::Tiny->read( INI_FILE );

print $conf->{hoge}->{fuga} # 第1:セクション 第2:設定

ループ

リスト

これ一択かな。forで回してもいいけど。
指摘があったので修正。こんな書き方できるのか

for my $val (@list){
    print $val;
}

ハッシュ

each使うより、keysで取得して回すほうが良い
sort使ってキーの昇順に回すのをよくやる
こっちも指摘があったので修正

for my $key (sort keys( %hash )){
    my $val = $hash{$key};
}

ファイルIO

2引数は悪だと思っている。3引数を推奨。
指摘があったので修正。レキシカル変数を使用する

第2引数 状態 書き方
< 読み込み用 open (my $fh, '<','file.txt')
> 書き込み用 open (my $fh, '>', 'file.txt');
>> 追加書き込み用 open (my $fh, '>>', 'file.txt');
+< <に加えて読み書き両用 open (my $fh, '+<', 'file.txt');
+> >に加えて読み書き両用 open (my $fh, '+<', 'file.txt');
+>> >>に加えて読み書き両用 open (my $fh, '+<', 'file.txt');

ファイル読込

    open($fh, '<', $file) or die("can't open file");    
    while(my $line = <$fh>){
        print $line;
    }

ファイル書き込み

    open($fh, '>', $file) or die("can't open file");    
    print $fh $hoge;

ファイルの削除

    unlink $file;

postgreSQL

接続

    my $dsn = "dbi:Pg:dbname=${db_name};host=${host};port=${port}";
    my $dbh = DBI->connect(
        $dsn,
        $username,
        $password,
        {
            AutoCommit => 0,
            RaiseError => 1,
            PrintError => 0,
        }
    ) or die("cannot connect $dsn:$!");
    $dbh->quote('');

SELECT

$sqlにSELECT用SQLを組み立てて、ステートメント取得、パラメータとともに実行する

    my $sth = $dbh->prepare("SELECT hoge FROM fuga WHERE hanya = ?");
    my $res = $select_sth->execute($param);

INSERT

$sqlにINSERT用SQLを組み立てて、ステートメント取得、パラメータとともに実行する

    my $sth = $dbh->prepare("INSERT INTO hoge (fuga1,fuga2,…) VALUES (?,?,…)");
    my $res = $select_sth->execute($param1,$param2,…);

UPDATE

$sqlにUPDATE用SQLを組み立てて、ステートメント取得、パラメータとともに実行する

    my $sth = $dbh->prepare("UPDATE hoge SET fuga = ? WHERE hanya = ?");
    my $res = $select_sth->execute($param1,$param2);
1
3
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3