In Perl, how can I create a hash, whose values will be t开发者_Python百科he address of a 2D array?
I need to get the values of the 2D array dynamically, too.Please give me the exact coding. I am breaking my head.
How about this?
my %hash = (
foo => [[1, 2], [3, 4]],
bar => [[5, 6], [7, 8]]
);
2D array is modelled as array of arrays here.
Arrays and hashes can only take scalar values, however an array reference (created using []
, among other ways) are scalars. Therefore creating nested arrays is done using this construct. Think of it as:
$array_element_1 = ['row 1 column 1', 'row 1 column 2'];
$array_element_2 = ['row 2 column 1', 'row 2 column 2'];
$array_reference = [$array_element_1, $array_element_2];
%hash = ( 'key' => $array_reference);
except without all of the intermediate storing. These are called anonymous references (since they don't require that you give the original structure a name before creating the reference to the structure). Note that anonymous hash references are created using {}
. Read more at perldoc perlreftut
.
精彩评论