Perl: How to Construct "Array of Array" Data Structure

Submitted by admin on Mon, 04/18/2016 - 12:06

How can we express the data structure of "Array of Array" in Perl? Usually we create a generic array in Perl like this: @array = ('aaa', 'bbb', 'ccc'). Please take a look at the sample code shown below.
Note that a vaiable $songs starts with '$'. Also note that parenthesis is [...], not (...), even it is inside the parenthesis. This is to express a "reference" of "Array of Array". Take a look at "foreach" for accessing the reference variable.
 
#!/usr/bin/perl

my $songs = [
[
'S3T-party_people.mp3' ,
'3MN-ill_do_my_best.mp3',
'CU2-gamusha_life.mp3' ,
'A3N-kaerimichi.mp3' ,
],
[
'4YK-tokyo_zekkei.mp3' ,
'BM3-karate.mp3' ,
'DE9-ashita_chikyuu_ga_konogoma.mp3',
'R3-bright_fantasy.mp3' ,
],
[
'IR3-realize.mp3' ,
'MCZ-hakkin_no_yoake.mp3' ,
'8AS-itsu_ka_mita_niji_no_sono_shita.mp3',
'WG3-shoujo_koukyoukyoku.mp3' ,
],
];

my $song_list = $songs->[1]; # Access to the second array set

foreach my $song (@$song_list) { # Put '@' before a variable $song_list

print "$song\n";
}

1;

Here is the output.
4YK-tokyo_zekkei.mp3
BM3-karate.mp3
DE9-ashita_chikyuu_ga_konogoma.mp3
R3-bright_fantasy.mp3

Tags