Perl中的非统一多维数组

时间:2019-01-17 11:44:09

标签: arrays perl

是否可以在Perl中定义可以具有非均匀维数的多维数组?像下面的例子一样?

Agenda = @( 'Monday' , {'Tuesday',Lunch} , 'Wednesday' , 'Thursday', {'Friday','Lunch','Dinner'}) 

注意第二个元素{'Tuesday',Lunch}本身是如何数组的。

1 个答案:

答案 0 :(得分:5)

是的,只需使用数组引用即可。使用JSON作为输出格式来说明您的示例:

use strict;
use warnings;

use JSON;

my @agenda = (
    'Monday',
    ['Tuesday', 'Lunch'],
    'Wednesday',
    'Thursday',
    ['Friday', 'Lunch', 'Dinner'],
);

print JSON->new->pretty->encode(\@agenda);

输出:

$ perl dummy.pl
[
   "Monday",
   [
      "Tuesday",
      "Lunch"
   ],
   "Wednesday",
   "Thursday",
   [
      "Friday",
      "Lunch",
      "Dinner"
   ]
]

编辑我个人将使用哈希引用列表,即

my @agenda = (
   {
       day    => 'Monday',
       events => [],
   },
   ...
   {
       day    => 'Friday',
       events => ['Lunch', 'Dinner'],
   },
   ...
);

foreach my $entry (@agenda) {
   my $day    = $entry->{day};
   my $events = $entry->{events};

   print $day . ": " . join(" ", @{ $events }) . "\n";
}

甚至为events使用哈希引用。