2012-11-14 52 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