请教关于perl二维数组的问题

lalio77 2011-03-27 02:54:09
初始化这样一个数组:@test=([1,2,3],[4,5,6],[7,8,9]);
$test[0]是一个引用。
$temp=$test[0];
print @$temp->[2];
这样可以输出test[0][2];
为何 @$test[0]->[2] 就啥也输不出?是优先级的关系么?

另外,对于一个二维甚至更高维的数组,怎样传递一个一维的参数给子函数呢?比如这个,怎么会什么都不输出呢?
sub fun
{
$temp=$_;
print @$temp,"\n";
}
fun($test[0]);
...全文
250 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
robinsooon 2011-03-27
  • 打赏
  • 举报
回复
改为如下代码也可以:
---------------------------------------
@test=([1,2,3],[4,5,6],[7,8,9]);

sub fun
{
my($temp)=(@_);
print @{$temp},"\n";
}
fun($test[0]);
---------------------------------------
lalio77 2011-03-27
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 witwolf 的回复:]
看perl实例精解,相当不错
[/Quote]

嗯,多谢推荐~~等看了手头这本吧,一步步来~~
lalio77 2011-03-27
  • 打赏
  • 举报
回复
测试了一下。。。得出这些结论,不知道对不对呢?

perl是把所有传进去的参数都放在子程序自己的@_中,就是变量"_"中,它是一个数组,可以通过使用shift移出来,也可以通过数组操作"$_[]"移出来

对于一维数组,my @test1=(1,2,3);传@test1,是把@test1里面的元素一个一个放到@_中;
对于二维数组,my @test2=[[1,2,3],[4,5,6]];传@test2,进去的就是数组@test2的引用;
对于二维数组,my @test3=([1,2,3],[4,5,6]);传@test3,分别把@test3中的两个数组的引用放入@_;

依据:

use strict;
use warnings;
sub fun
{
my $cs=$#_+1;
print "the num of member in \@_ is:";
print $cs,"\n";
for my $j(0..$cs)
{print "$_[$j]","\n";}

}


还请各位大神指点,小弟这不胜感激。
witwolf 2011-03-27
  • 打赏
  • 举报
回复
看perl实例精解,相当不错
lalio77 2011-03-27
  • 打赏
  • 举报
回复
嗯~~多谢指正
初学perl,《perl语言入门》里面貌似没有讲到二维数组。。。
第二个问题我再研究下~~参数传递这块也很不了解,不知道各种类型传进去的是什么,要学习的还有很多~~
iambic 2011-03-27
  • 打赏
  • 举报
回复
难道写代码不加use strict和use warnings?自己看下下面代码的输出:
use strict;
use warnings;

my @test=([1,2,3],[4,5,6],[7,8,9]);

my $temp=$test[0];
print @$temp->[2], "\n";

print @$test[0]->[2], "\n";

引用和数据结构的组合搞不清楚的话去阅读Intermediate Perl。这样靠瞎猜把把代码跑起来不好的。

正确的使用:
use strict;
use warnings;

my @test=([1,2,3],[4,5,6],[7,8,9]);

my $temp=$test[0];
print $temp->[2], "\n";

print $test[0]->[2], "\n";


推荐使用:
use strict;
use warnings;

my $test = [[1,2,3],[4,5,6],[7,8,9]];
print $test->[0][2], "\n";



后面的那个问题搞清楚$_和@_的区别。

最后重申一次,写代码不加use strict;和use warnings;是浪费别人也浪费自己的时间。

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧