2014-04-16 28 views
0

我正在制作一个快速而肮脏的书籍标题排列,其中标题按照货架码,然后由作者,然后按标题排列。元标签的数量可能会有所不同(按货架号,国家,然后是作者,最终标题或类别排序),并且元素的数量可能会有所不同。从单个阵列创建多个卡片条目

我有作为排序顺序

my @Stapel = ("133 ; 101", "smith ; jones ; harrods", "The Book of Kelts") ; 

保持3元标记(shelfcode,AUTHORNAME,标题),其中所述第一元标记具有2个elemetns,第二个保持3个elemetns和最后元标记保持一个元件。

我想有什么样的输出下面每个标题由shelfcode首先安排,然后由每个作者再由标题:

101  harrods The Book of Kelts 
101  jones The Book of Kelts 
101  smith The Book of Kelts 
133  harrods The Book of Kelts 
133  jones The Book of Kelts 
133  smith The Book of Kelts 

我至今我想要做什么就做,但它是所有硬编码和过于简单:

# Create an array of arrays of each element 
foreach (@Stapel) { 
    my @s = split/;/; 
    print "\n - subarray has " . @s . " elements which are: '@s'" ; 
    push @BIG, ([@s]) ; 
} 

for ($p=0 ; $p<@BIG ; $p++) {  
    foreach (sort @{ $BIG[$p] } ) { 
     $a = $_ ; 
     foreach (sort @{ $BIG[$p+1] } ) { 
      $b = $_ ; 
      foreach (@{ $BIG[$p+2] } ) { 
       $c = $_ ; 
       $Entry = "$a\t$b\t$c" ; 
       print "\n$Entry" ; 
      } 
     } 
    } 
} # for 

我如何着手做这更加灵活,即每元标记可能会有所不同元素的数量,和元标记的数量也可以变化。我试图在这里使用递归,但我很困惑。

回答

0

你可以使用哈希数组:

#!/usr/bin/perl 
use strict; 
use warnings; 

my @Stapel = ("133 ; 101", "smith ; jones ; harrods", "The Book of Kelts") ; 

sub arr_to_hash { # converts your array to an hash 
    my $arr = shift; 
    my %hash =(); 
    $hash{shelfcode} = [ split /\s*;\s*/, $arr->[0] ]; 
    $hash{authorname} = [ split /\s*;\s*/, $arr->[1] ]; 
    $hash{title} = $arr->[2]; 
    return %hash; 
} 

my %stapel_hash = arr_to_hash(\@Stapel); 

for my $shelfcode (sort @{$stapel_hash{shelfcode}}) { 
    for my $author (sort @{$stapel_hash{authorname}}) { 
    print "$shelfcode\t$author\t$stapel_hash{title}\n"; 
    } 
} 

我认为这几乎是相同的复杂性,但它是一个更灵活一点。

+0

这是,但是,问题仍然是,哈希的数量可能会有所不同,也应该是可变的。或者,在你的例子中,它可能是一个额外的散列,如language => [“en”,“de”], – Harry

+0

呃..散列是许多'key =>值的集合,所以如果你想要添加另一个指向数组['“en”,“it”,“de”,..]的关键字'language',你可以很容易地做到这一点看看我贴的代码。注意到,与那些接近你的脚本,计算复杂度增加!请考虑接受我的答案,如果是这样的权利! –