--- title: ハッシュの扱い方について author: kazu634 date: 2009-03-08 wordtwit_post_info: - 'O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:4517;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}' categories: - Perl ---
Perlでスクリプトを書いていてはまったので、とりあえず備忘録としてまとめておきます。
my %month = ( January => 1, Feburary => 2, March => 3, April => 4, May => 5, June => 6, July => 7, August => 8, September => 9, October => 10, November => 11, December => 12, ); # ハッシュリファレンスを$ref_hashに格納 my $ref_hash = \%month; print("reference to month: $ref_hash\n"); # デリファレンスするには%$ref_hashのように表記する my @sorted_key = sort keys %$ref_hash; print("Sorted key: @sorted_key\n");
ハッシュリファレンスからのハッシュの要素にアクセスするには次のような方法がある:
- $$ref_hash{January} - $ref_hash->{January}
無名ハッシュは「{}」で指定してあげる:
my $ref_hash = { January => 1, Feburary => 2, March => 3, April => 4, May => 5, June => 6, July => 7, August => 8, September => 9, October => 10, November => 11, December => 12, };
こんな感じで書くといい:
while (<DATA>) { chomp; if (/^\[(.*)\]$/) { $tmp_key = $1; } elsif (/^(.*): (.*)$/) { $data{$tmp_key}{$1} = $2; } } # print Dumper(%data); } __DATA__ [total_income] income: 227706 extra_income: 15000 [fixed_pay] cell_phone1: 2213 cell_phone2: 9750 meals: 13230 scholarship: 9000 provider: 4095 [commute] commute: 39890 [daily_pay] 2/01: 7130 2/02: 1044 2/03: 1710 2/04: 9360 2/05: 6810 2/06: 1405 2/07: 7608 2/08: 670 2/09: 1374 2/10: 3059 2/11: 5205 2/12: 1470 2/13: 750 2/14: 407 2/15: 2774 2/16: 2510 2/17: 1320 2/18: 1740 2/19: 6910 2/20: 2837 2/21: 7620 2/22: 6277 2/23: 1730 2/24: 2624 2/25: 4347 2/26: 1299 2/27: 987 2/28: 4900