Perl 的三维数组怎么实现?

软件和网站开发以及相关技术探讨
回复
头像
Tobey
帖子: 178
注册时间: 2006-03-30 13:34

Perl 的三维数组怎么实现?

#1

帖子 Tobey » 2008-09-01 19:29

关联数组可以用3维?
怎么写?
heejun
帖子: 60
注册时间: 2006-05-01 12:29
来自: zju

#2

帖子 heejun » 2008-09-05 15:34

perl里面的数组是一维的
但是你可以用引用实现任意维的数组
可以用数组也可以用hash来实现
具体可以看intermediate perl programming
这里给出一种数组的实现

代码: 全选

#!/usr/bin/perl 
#===============================================================================
#
#         FILE:  dimension.pl
#
#        USAGE:  ./dimension.pl 
#
#  DESCRIPTION:  
#
#      OPTIONS:  ---
# REQUIREMENTS:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:  kernel (Mr), <firefoxelectric@gmail.com>
#      COMPANY:  Gentoo GNU/Linux
#      VERSION:  1.0
#      CREATED:  09/05/2008 03:21:17 PM CST
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;
#A reference to three dimesion array
my $dimension;
#Initialization
#3x3x3
#Value range from 000 to 333
foreach ( 0.. 3 ){
	my $i = $_;
	foreach ( 0..$i){
		my $j = $_;
		foreach(0..$j){
			my $k = $_;
			$dimension->[$i]->[$j]->[$k] = "$i$j$k";
		}
	}
}

#Print out the value
#
foreach ( 0..3){
	my $i = $_;
	foreach (0..$i){
		my $j=$_;
		foreach(0..$j){
			my $k =$_;
			print "Index[$i][$j][$k] is :",$dimension->[$i][$j][$k],"\n";
		}
	}
}
运行结果
Index[0][0][0] is :000
Index[1][0][0] is :100
Index[1][1][0] is :110
Index[1][1][1] is :111
Index[2][0][0] is :200
Index[2][1][0] is :210
Index[2][1][1] is :211
Index[2][2][0] is :220
Index[2][2][1] is :221
Index[2][2][2] is :222
Index[3][0][0] is :300
Index[3][1][0] is :310
Index[3][1][1] is :311
Index[3][2][0] is :320
Index[3][2][1] is :321
Index[3][2][2] is :322
Index[3][3][0] is :330
Index[3][3][1] is :331
Index[3][3][2] is :332
Index[3][3][3] is :333
头像
Tobey
帖子: 178
注册时间: 2006-03-30 13:34

#3

帖子 Tobey » 2008-09-06 14:21

谢谢。

我现在的是hash,
而且是不定长的。
细想一下,
其实不是三维的。
只是有两层键值对应关系而已。
不过把一层转换成了用符号分割的字串。
回复