| | 74 | |
| | 75 | == データの永続化 == |
| | 76 | Storable を使って文字列で Perl オブジェクトをやりとりしてみる.nfreeze を使う場合,改行をエスケープする必要があるようだ. |
| | 77 | |
| | 78 | バイナリでのやりとりも可であれば,nstore を使うのが良い. |
| | 79 | |
| | 80 | * freeze.pl |
| | 81 | {{{ |
| | 82 | #!perl |
| | 83 | #!/usr/bin/perl |
| | 84 | |
| | 85 | use strict; |
| | 86 | use diagnostics; |
| | 87 | use warnings; |
| | 88 | use Storable qw(nfreeze); |
| | 89 | |
| | 90 | my $hash = { |
| | 91 | "1" => "hogera", |
| | 92 | "2" => 1, |
| | 93 | "3" => [1, 2, 3], |
| | 94 | "4" => {"a" => 1}, |
| | 95 | "5" => { |
| | 96 | "a" => 1, |
| | 97 | "b" => [1, 2, 3], |
| | 98 | "c" => {"i" => 2}, |
| | 99 | }, |
| | 100 | }; |
| | 101 | |
| | 102 | my $serialized = nfreeze($hash); |
| | 103 | print r_escape($serialized); |
| | 104 | |
| | 105 | sub r_escape { |
| | 106 | my $s = shift; |
| | 107 | $s =~ s/([%\r\n])/sprintf("%%%02X", ord($1))/ge; |
| | 108 | return $s; |
| | 109 | } |
| | 110 | |
| | 111 | }}} |
| | 112 | |
| | 113 | * thaw.pl |
| | 114 | {{{ |
| | 115 | #!perl |
| | 116 | #!/usr/bin/perl |
| | 117 | |
| | 118 | use strict; |
| | 119 | use diagnostics; |
| | 120 | use warnings; |
| | 121 | use Storable qw(thaw); |
| | 122 | use Data::Dumper; |
| | 123 | |
| | 124 | my $line = ""; |
| | 125 | $line .= $_ while (<>); |
| | 126 | |
| | 127 | my $hash = thaw(r_unescape($line)); |
| | 128 | print Dumper($hash); |
| | 129 | |
| | 130 | sub r_unescape { |
| | 131 | my $s = shift; |
| | 132 | $s =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge; |
| | 133 | return $s; |
| | 134 | } |
| | 135 | }}} |
| | 136 | |
| | 137 | * 実行結果 |
| | 138 | {{{ |
| | 139 | #!sh |
| | 140 | $ ./freeze.pl | ./thaw.pl |
| | 141 | $VAR1 = { |
| | 142 | '1' => 'hogera', |
| | 143 | '4' => { |
| | 144 | 'a' => 1 |
| | 145 | }, |
| | 146 | '3' => [ |
| | 147 | 1, |
| | 148 | 2, |
| | 149 | 3 |
| | 150 | ], |
| | 151 | '2' => 1, |
| | 152 | '5' => { |
| | 153 | 'c' => { |
| | 154 | 'i' => 2 |
| | 155 | }, |
| | 156 | 'a' => 1, |
| | 157 | 'b' => [ |
| | 158 | 1, |
| | 159 | 2, |
| | 160 | 3 |
| | 161 | ] |
| | 162 | } |
| | 163 | }; |
| | 164 | }}} |