Snippets

sironekotoro コマンド実行時の引数にファイル名を指定し、中でハッシュにする

Created by sironekotoro
use strict;
use warnings;
use Data::Dumper;

# 以下のように実行した時
# perl hoge.pl --config hoge.txt
# hoge.pl と hoge.txt は同じ場所にあるとする

my $option = $ARGV[0];                  # --config が入る
my $file   = $ARGV[1] // 'hoge.txt';    # hoge.txt が入る;

my %hash = ();                          # hoge.txtの中身格納用

# ファイルのオープン方法は以下のページとか参考
# http://d.hatena.ne.jp/perlcodesample/20110212/1303702930
# Perl入学式だと2012年の資料の後半にあった
# http://www.perl-entrance.org/static/handout/2012/perlentrance05/index.html#/title
open my $FH, "<", $file or die;
for my $line (<$FH>) {
    chomp $line;
    my ( $key, $value ) = split /=/, $line;
    $hash{$key} = $value;
}
close $FH;

print Dumper \%hash;

# $VAR1 = {
#           'hostname' => 'host.com',
#           'password' => 'hogepass',
#           'user' => 'hogehoge'
#         };
1
2
3
hostname=host.com
user=hogehoge
password=hogepass

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.