匹配并且如果已经存在则不执行任

时间:2013-05-06 15:04:30

标签: arrays perl excel spreadsheet

我还需要一些帮助。

我正在尝试创建一个我从Excel电子表格调用的项目列表。 假设列A包含国家列表。

America
South Africa
Belgium
America

现在相应行中的国家/地区附加了其他项目,但是在D列,因此其他列中可能有更多项目与第一个单元格中的国家/地区相对应,如下所示。

______________A__________________________B___________________C___________

---------------|----------------|-------------|

America........|..Samsung.......|...1234......|

South Africa...|..Dell..........|...54321.....|

Belgium........|..iPhone........|...2345......|

America........|..Nokia.........|...9876......|

我想将它发布到XML表格,但我不想多次创建每个国家/地区,所以我想检查行的输入,如果它不存在,则创建它。所以在上面的表格中,我有两次美国,但它需要创建一次仅作为XML条目的美国,并从那里我将附加其他项目。

现在我通过计算工作表中的行来获取行数据,因为它每次都会有所不同,然后我需要开始编写XML。

use Spreadsheet::Read;

#use XML::Writer

my $book = ReadData("InfoDB.xlsx");

my @rows = Spreadsheet::Read::rows($book->[1]);

my $count = 1;

my @clause_all;

foreach $tab (@rows) {
    $count++;
    @row = Spreadsheet::Read::cellrow($book->[1], $count);
    @country = $row[1];
}

如果有人可以帮我把这个匹配到一个数组中,或者某种程度上会很棒! 我尝试了很多方法,但是无法得到完美的结果,如果我发布了每次尝试的尝试,我真的会厌烦你。 :(

2 个答案:

答案 0 :(得分:0)

有些事情:

my @country;
foreach my $tab (@rows) {
    ...

    # The smart match operator (~~) will return true if the value on the
    # left is found in the list on the right.
    unless ($row[1] ~~ @country) {
        # do the things you need to do then add the country to the list
        push @country, $row[1];
    }
}

答案 1 :(得分:0)

创建哈希,使用国家/地区名称作为键: 然后将新数据推送到存储在该密钥的数组引用上 - 这是伪代码。你需要在电子表格中疯狂地使其发挥作用。

%countries = ();
foreach my $row ( @rows) {
  my ($country, $thing, $number) = row2columns($row);
  push @{ $countries{$country} }, [ $thing, $number ];
}

现在你有一个大的哈希值,你可以用你喜欢的方式转换为XML。