Perl中的非均匀多维数组

use*_*125 1 arrays perl

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

Agenda = @( 'Monday' , {'Tuesday',Lunch} , 'Wednesday' , 'Thursday', {'Friday','Lunch','Dinner'}) 
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*ker 5

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

use strict;
use warnings;

use JSON;

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

print JSON->new->pretty->encode(\@agenda);
Run Code Online (Sandbox Code Playgroud)

输出:

$ perl dummy.pl
[
   "Monday",
   [
      "Tuesday",
      "Lunch"
   ],
   "Wednesday",
   "Thursday",
   [
      "Friday",
      "Lunch",
      "Dinner"
   ]
]
Run Code Online (Sandbox Code Playgroud)

编辑我个人会使用散列引用列表,即

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";
}
Run Code Online (Sandbox Code Playgroud)

甚至使用散列引用events.