2012-11-14 51 views
0

我想存儲一個ini文件的數據。如何將立方體方法存儲在perl中。我如何存儲立方體方法

我嘗試:

stylesheet.ini:

p indent noindent 
h1 heading1 
h2 heading2 
h3 heading3 
h4 heading4 
h5 heading5 
h6 heading6 
disp-quote blockquote 

腳本:

my %stylehash; 
open(INI, 'stylesheet.ini') || die "can't open stylesheet.ini $!\n"; 
my @style = <INI>; 
foreach my $sty (@style){ 
     chomp($sty); 
     split /\t/, $sty; 
     $stylehash{$_[0]} = [$_[1], $_[2], $_[3], $_[4]]; 
} 

print $stylehash{"h6"}->[0]; 

在這裏,我分配$ [2],$ [3],$ _ [4 ]不需要的數組,因爲第一個P標籤將獲得兩個數組,然後h1獲得一個數組。我怎樣才能完美存儲,如何檢索它。

我需要:

$stylehash{$_[0]} = [$_[1], $_[2]]; #p tag 
$stylehash{$_[0]} = [$_[1]]; #h1 tag 

print $stylehash{"h1"}->[0]; 
print $stylehash{"p"}->[0]; 
print $stylehash{"p"}->[1]; 

我怎麼可以存儲立方體的方法。標記始終是唯一的,風格名稱隨機增加或減少。我怎麼解決這個問題。

+1

'立方體法'究竟是什麼? – ugexe

+0

my%cube =('$ _ [0]',[$ _ [1],$ _ [2]],'$ _ [0]',[$ _ [1]],);在這裏我會舉例,$ _ [0]是uniq鍵,但值是不同大小的數組,我不能直接存儲在ini文件上面。我可以輕鬆回收,但無法爲每個鍵存儲數組的差異大小。 – user1811486

+1

不推薦使用'split'在void上下文中將結果賦給'@ _'的功能。謹慎使用。 – mob

回答

5

如果我理解正確,你有一堆鍵值列表。也許一個價值,也許兩個,也許三個......而你想存儲這個。最簡單的做法是將其構建爲列表哈希,並使用預先存在的數據格式,例如JSON,它很好地處理Perl數據結構。

use strict; 
use warnings; 
use autodie; 

use JSON; 

# How the data is laid out in Perl 
my %data = (
    p  => ['indent', 'noindent'], 
    h1 => ['heading1'], 
    h2 => ['heading2'], 
    ...and so on... 
); 

# Encode as JSON and write to a file. 
open my $fh, ">", "stylesheet.ini"; 
print $fh encode_json(\%data); 

# Read from the file and decode the JSON back into Perl. 
open my $fh, "<", "stylesheet.ini"; 
my $json = <$fh>; 
my $tags = decode_json($json); 

# An example of working with the data. 
for my $tag (keys %tags) { 
    printf "%s has %s\n", $tag, join ", ", @{$tags->{$tag}}; 
} 

更多與hashes of arrays一起使用。

+0

k謝謝你,它工作得很好 – user1811486