Learning Perl: 4.9. The return Operator

Previous Page

Next Page

 

4.9. The return Operator

The return operator immediately returns a value from a subroutine:

    my @names = qw/ fred barney betty dino wilma pebbles bamm-bamm /;
    my $result = &which_element_is("dino",@names);

    sub which_element_is {
      my($what,@array) = @_;
      foreach (0..$#array) {  # indices of @array's elements
        if ($what eq $array[$_]) {
          return $_;         # return early once found
        }
      }
      -1;                    # element not found (return is optional here)
    }

This subroutine is being used to find the index of "dino" in the array @names. First,the my declaration names the parameters: there's $what,which is what we're searching for,and @array,an array of values to search within. That's a copy of the array @names in this case. The foreach loop steps through the indices of @array (the first index is 0,and the last one is $#array,as you saw in Chapter 3).

Each time through the foreach loop,we check to see whether the string in $what is equal[*] to the element from @array at the current index. If it's equal,we return that index at once. This is the most common use of the keyword return in Perlto return a value immediately without executing the rest of the subroutine.

[*] You noticed that we used the string equality test,eq,instead of the numeric equality test,= =,didn't you?

What if we never found that element? In that case,the author of this subroutine has chosen to return -1 as a "value not found" code. It would be more Perlish,perhaps,to return undef in that case,but this programmer used -1. Saying return -1 on that last line would be correct,but the word return isn't needed.

Some programmers like to use return every time there's a return value as a means of documenting that it is a return value. For example,you might use return when the return value is not the last line of the subroutine,such as in the subroutine &larger_of_fred_or_barney earlier in this chapter. It's not needed,but it doesn't hurt anything. However,many Perl programmers believe it's just an extra seven characters of typing.

4.9.1. Omitting the Ampersand

A few rules govern when a subroutine call can omit the ampersand. If the compiler sees the subroutine definition before invocation or if Perl can tell from the syntax that it's a subroutine call,the subroutine can be called without an ampersand,like a built-in function. (But there's a catch hidden in those rules,as you'll see in a moment.)

This means that if Perl can see that it's a subroutine call without the ampersand from the syntax alone,that's generally fine. That is,if you've got the parameter list in parentheses,it's got to be a function[

] call:

[

] In this case,the function is the subroutine &shuffle. But it may be a built-in function as you'll see in a moment.

    my @cards = shuffle(@deck_of_cards);  # No & necessary on &shuffle

If Perl's internal compiler has seen the subroutine definition,that's generally okay,too; in that case,you can omit the parentheses around the argument list:

    sub division {
      $_[0] / $_[1];                   # Divide first param by second
    }

    my $quotient = division 355,113;  # Uses &division

This works because of the rule that parentheses may always be omitted except when doing so would change the meaning of the code.

But don't put that subroutine declaration after the invocation,or the compiler won't know what the attempted invocation of division is all about. The compiler has to see the definition before the invocation to use the subroutine call as if it were a built-in.

That's not the catch,though. The catch is this: if the subroutine has the same name as a Perl built-in,you must use the ampersand to call it. With an ampersand,you're sure to call the subroutine; without it,you can get the subroutine only if there's no built-in with the same name:

    sub chomp {
      print "Munch,munch!/n";
    }

    &chomp;  # That ampersand is not optional!

Without the ampersand,we'd be calling the built-in chomp,even though we've defined the subroutine &chomp. So,the real rule to use is this one: until you know the names of all of Perl's built-in functions,always use the ampersand on function calls. That means that you will use it for your first hundred programs or so. But when you see someone else has omitted the ampersand in their own code,it's not necessarily a mistake; perhaps they know that Perl has no built-in with that name.[*] When programmers plan to call their subroutines as if they were calling Perl's built-ins,often when writing modules,they often use prototypes to tell Perl about the parameters to expect. Making modules is an advanced topic though; when you're ready for that,see Perl's documentation (in particular,the perlmod and perlsub documents) for more information about subroutine prototypes and making modules.

[*] Then again,maybe it is a mistake; you can search the perlfunc and perlop manpages for that name to see if it's the same as a built-in. And Perl will usually be able to warn you about this when you have warnings turned on.

Previous Page

Next Page

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(<>){ chomp; print "$_n" unless
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据进行拼凑,然后将拼凑后的数据用“|”连接在一起。表格内容如下: 员工号码员工姓名职位入职日期1001张三销售1980/12/17 0:00:
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,还不能保证书写一定正确。写了个Perl脚本,可快速构造MySQL脚本语句。脚本如下:#!/usr/bin/perluse strict;m
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了一个表的数据量统计日报,主要是针对数据库中使用较频繁,数据量又较大的31张表。该日报有两个sheet组成,第一个sheet是数据填写,第二个sh
在实际生产环境中,常常需要从后台日志中截取报文,报文的形式类似于.........一个后台日志有多个报文,每个报文可由操作流水唯一确定。以前用AWK写过一个,程序如下:beginline=`awk &
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让人领略到perl正则表达式的强大,程序如下:#!/usr/bin/perluse strict;my (%hash,%hash1,@arra
忍不住在 PerlChina 邮件列表中盘点了一下 Perl 里的 Web 应用框架(巧的是 PerlBuzz 最近也有一篇相关的讨论帖),于是乎,决定在我自己的 blog 上也贴一下 :) 原生 CGI/FastCGI 的 web app 对于较小的应用非常合适,但稍复杂一些就有些痛苦,但运行效率是最高的 ;) 如果是自己用 Perl 开发高性能的站,多推荐之。 Catalyst, CGI::A
bless有两个参数:对象的引用、类的名称。 类的名称是一个字符串,代表了类的类型信息,这是理解bless的关键。 所谓bless就是把 类型信息 赋予 实例变量。 程序包括5个文件: person.pm :实现了person类 dog.pm :实现了dog类 bless.pl : 正确的使用bless bless.wrong.pl : 错误的使用bless bless.cc : 使用C++语言实
gb2312转Utf的方法: use Encode; my $str = "中文"; $str_cnsoftware = encode("utf-8", decode("gb2312", $str));   Utf转 gb2312的方法: use Encode; my $str = "utf8中文"; $str_cnsoftware = encode("gb2312", decode("utf-8
  perl 计算硬盘利用率, 以%来查看硬盘资源是否存在IO消耗cpu资源情况; 部份代码参考了iostat源码;     #!/usr/bin/perl use Time::HiRes qw(gettimeofday); use POSIX; $SLEEPTIME=3; sub getDiskUtl() { $clock_ticks = POSIX::sysconf( &POSIX::_SC_
1 简单变量 Perl 的 Hello World 是怎么写的呢?请看下面的程序: #!/usr/bin/perl print "Hello World" 这个程序和前面 BASH 的 Hello World 程序几乎相同,只是第一行换成了 #!/usr/bin/perl ,还有显示的时候用的是 print,而不是 echo。有了前面 BASH 基础和 C 语言的基础,许多 Perl 的知识可以很
本文介绍Perl的Perl的简单语法,包括基本输入输出、分支循环控制结构、函数、常用系统调用和文件操作,以及进程管理几部分。 1 基本输入输出 在 BASH 脚本程序中,我们用 read var 来实现从键盘的输入,用 echo $var 来实现输出。那么在 Perl 中将有一点变化。Perl 中将标准输入用关键词 表示;标准输出用 表示,标准错误输出用 表示。故而从标准输入读取数据可以写成: $
正则表达式是 Perl 语言的一大特色,也是 Perl 程序中的一点难点,不过如果大家能够很好的掌握他,就可以轻易地用正则表达式来完成字符串处理的任务,当然在 CGI 程序设计中就更能得心应手了。下面我们列出一些正则表达式书写时的一些基本语法规则。 1 正则表达式的三种形式 首先我们应该知道 Perl 程序中,正则表达式有三种存在形式,他们分别是: 匹配:m/<regexp>/ (还可以简写为 /
在学习Perl和Shell时,有很多人可能会问这样一个问题,到底先学习哪个或者学习哪个更好! 每个人都有自己的想法,以下是个人愚见,请多多指教! Perl是larry wall为解决日常工作中的一个编程问题而产生的,它最初的主要功能是用于分析基于文本的数据和生成这些数据的统计和结果;尽管初衷很简单,但是后来发展了很多特点: 1、Perl是一种借鉴了awk、C、sed、shell、C++、Java等
Perl 有很多命令行参数. 通过它, 我们有机会写出更简单的程序. 在这篇文章里我们来了解一些常用的参数. (重点提示:在window下执行命令行程序的方式为 : perl -e "some code", 注意:是双引号啊,不是单引号,linux下执行时单引号) Safety Net Options 在使用 Perl 尝试一些聪明( 或 stupid) 的想法时, 错误难免会发生. 有经验的 P
转自: http://bbs.chinaunix.net/thread-1191868-1-1.html# 让你的perl代码看起来更像perl代码,而不是像C或者BASIC代码,最好的办法就是去了解perl的内置变量。perl可以通过这些内置变量可以控制程序运行时的诸多方面。 本文中,我们一起领略一下众多内置变量在文件的输入输出控制上的出色表现。 行计数 我决定写这篇文章的一个原因就是,当我发现
2009-02-02 13:07 #!/usr/bin/perl # D.O.M TEAM - 2007 # anonyph; arp; ka0x; xarnuz # 2005 - 2007 # BackConnectShell + Rootlab t00l # priv8! # 3sk0rbut0@gmail.com # # Backconnect by data cha0s (modifica
转自: http://bbs.chinaunix.net/thread-1191868-1-1.html# 让你的perl代码看起来更像perl代码,而不是像C或者BASIC代码,最好的办法就是去了解perl的内置变量。perl可以通过这些内置变量可以控制程序运行时的诸多方面。 本文中,我们一起领略一下众多内置变量在文件的输入输出控制上的出色表现。 行计数 我决定写这篇文章的一个原因就是,当我发现
黑莓 手机 屏幕发展历程对比 blackberry 各型号屏幕大小   黑莓手 机 一直在不断发展且新机型 也在不断上市. 因此,不同黑莓机型的屏幕分辨率也在不断变化着. 总的来说,屏幕分辨率一直在提高并且越来越清晰.我们对所有的黑莓 机型的屏幕分辨率做了个对比.~51blackberry ~com     可能大家特别感兴趣是新发布的黑莓机型,它的分辨率也是黑莓 机型中前所未有的.   黑莓 b
      公司里没有我用惯的UltraEdit的lisence了, 只能无奈转向开源的Notepad++, 找了半天才知道配置运行Perl的办法。         1,用Notepad++打开.pl文件,         2, F5或者Run->Run,打开运行窗口,在下面的框框里输入:Perl -w "$(FULL_CURRENT_PATH)", 然后Save,保存成一个命令就行,名字比如叫R