免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3127 | 回复: 4
打印 上一主题 下一主题

perl引用的一个例子,供初学者参考。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-06-24 12:30 |只看该作者 |倒序浏览
下面的例子演示了perl引用的基本特性,供初学的同好们参考。

  1. #!/usr/bin/perl
  2. use strict;

  3. sub add
  4. {
  5.     my ($ref0, $ref1) = @_;
  6.     my $len = @$ref0;
  7.     my $sum = 0;
  8.     for (my $i = 0; $i < $len; $i++) {
  9.         $sum += $ref0->[$i] + $ref1->[$i];
  10.     }
  11.     return $sum;
  12. }

  13. my @arr0 = (1, 1, 1);
  14. my @arr1 = (2, 2, 2);
  15. print add(\@arr0, \@arr1);
  16. # 输出结果为 (1+2) + (1+2) + (1+2) = 9

  17. my $ref0 = [1, 1, 1];
  18. my $ref1 = [3, 3, 3];
  19. print add($ref0, $ref1);
  20. # 输出结果为 (1+3) + (1+3) + (1+3) = 12
复制代码

perl区分值类型和引用类型,传递参数时使用的是按值传递,所以代码和java/python有很大的不同。

[ 本帖最后由 bibi2008 于 2008-6-24 12:34 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-06-24 13:09 |只看该作者
perl中函数的参数应该是别名

论坛徽章:
0
3 [报告]
发表于 2008-06-24 13:22 |只看该作者
原帖由 gawk 于 2008-6-24 13:09 发表
perl中函数的参数应该是别名


在perl中,参数传递和赋值都是值拷贝,以下是一个例子

  1. #!/usr/bin/perl

  2. @arr1 = (1, 2, 3);
  3. @arr2 = @arr1;  
  4. push @arr2, 4;

  5. $len1 = @arr1;
  6. $len2 = @arr2;
  7. print "len1 = $len1, len2 = $len2\n";
  8. # 输出结果: len1 = 3, len2 = 4
复制代码

论坛徽章:
0
4 [报告]
发表于 2008-06-24 13:32 |只看该作者
那你在函数中修改一下传递的参数看看
然后在函数调用后再打印一下参数看看

下面这段话摘自perldoc perlsub中
Any arguments passed in show up in the array @_. Therefore, if you
called a function with two arguments, those would be stored in $_[0] and
$_[1]. The array @_ is a local array, but its elements are aliases for
the actual scalar parameters
. In particular, if an element $_[0] is
updated, the corresponding argument is updated (or an error occurs if it
is not updatable). If an argument is an array or hash element which did
not exist when the function was called, that element is created only
when (and if) it is modified or a reference to it is taken. (Some
earlier versions of Perl created the element whether or not the element
was assigned to.) Assigning to the whole array @_ removes that aliasing,
and does not update any arguments.

[ 本帖最后由 gawk 于 2008-6-24 13:37 编辑 ]

论坛徽章:
0
5 [报告]
发表于 2008-06-24 14:54 |只看该作者
引用的时候的确要小心,函数引用的时候最好加上"&".
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP