Learning Perl: 3.7. Scalar and List Context

Previous Page

Next Page

 

3.7. Scalar and List Context

This is the most important section in this chapter. In fact,it's the most important section in the entire book. It wouldn't be an exaggeration to say that your entire career in using Perl will depend upon understanding this section. If you've gotten away with skimming the text up to this point,this is where you should pay attention.

That's not to say that this section is in difficult to understand. It's a simple idea: a given expression may mean different things depending upon where it appears. This is nothing new; it happens all the time in natural languages. For example,in English,[*] suppose someone asked you what the word "read"[

] means. It has different meanings depending on how it's used. You can't identify the meaning until you know the context.

[*] If you aren't a native speaker of English,this analogy may not be obvious to you. But context sensitivity happens in every spoken language,so you may be able to think of an example in your own language.

[

] Or maybe they were asking what the word "red" means,if they were speaking rather than writing a book. It's ambiguous either way. As Douglas Hofstadter said,no language can express every thought unambiguously,especially this one.

The context refers to where an expression is found. As Perl is parsing your expressions,it always expects a scalar or list value.[*] What Perl expects is called the context of the expression.[

]

[*] Unless,of course,Perl is expecting something else entirely. There are other contexts that aren't covered here. Nobody knows how many contexts Perl uses; the biggest brains in all of Perl haven't agreed on an answer.

[

] This is no different than what you're used to in human languages. If I make a grammatical mistake,you notice it right away because you expect certain words in certain places. Eventually,you'll read Perl this way,too,but at first you have to think about it.

    42 + something # The something must be a scalar
    sort something # The something must be a list

If something is the exact same sequence of characters,in one case it may give a single,scalar value,and in another,it may give a list.[

] Expressions in Perl always return the appropriate value for their context. For example,how about the "name"[§] of an array. In a list context,it gives the list of elements. But in a scalar context,it returns the number of elements in the array:

[

] The list may be one element long,of course. It could also be empty,or it could have any number of elements.

[§] Well,the true name of the array @people is people. The @ sign is a qualifier.

    @people = qw( fred barney betty );
    @sorted = sort @people; # list context: barney,betty,fred
    $number = 42 + @people;  # scalar context: 42 + 3 gives 45

Even ordinary assignment (to a scalar or a list) causes different contexts:

    @list = @people; # a list of three people
    $n = @people;    # the number 3

Don't jump to the conclusion that scalar context always gives the number of elements that would have been returned in list context. Most list-producing expressions[**] return something more interesting than that.

[**] With regard to the point of this section,there's no difference between a "list-producing" expression and a "scalar-producing" one. Any expression can produce a list or a scalar,depending upon context. So when we say "list-producing expressions," we mean expressions that are typically used in a list context and that might surprise you when they're used unexpectedly in a scalar context (like reverse or @fred).

3.7.1. Using List-Producing Expressions in Scalar Context

There are many expressions that would typically be used to produce a list. If you use one in a scalar context,what do you get? See what the author of that operation says about it. Usually,that person is Larry,and usually the documentation gives the whole story. A big part of learning Perl is learning how Larry thinks.[

] Therefore,once you can think like Larry does,you know what Perl should do. But while you're learning,you'll probably need to look into the documentation.

[

] This is only fair since while writing Perl he tried to think like you do to predict what you would want.

Some expressions don't have a scalar-context value at all. For example,what should sort return in a scalar context? You wouldn't need to sort a list to count its elements,so until someone implements something else,sort in a scalar context always returns undef.

Another example is reverse. In a list context,it gives a reversed list. In a scalar context,it returns a reversed string (or reversing the result of concatenating all the strings of a list,if given one):

    @backwards = reverse qw/ yabba dabba doo /;
       # gives doo,dabba,yabba
    $backwards = reverse qw/ yabba dabba doo /;
       # gives oodabbadabbay

At first,it's not always obvious if an expression is being used in a scalar or a list context. But,trust us,it will become second nature for you eventually.

Here are some common contexts to start you off:

    $fred = something;            # scalar context
    @pebbles = something;         # list context
    ($wilma,$betty) = something; # list context
    ($dino) = something;          # still list context!

Don't be fooled by the one-element list; that last one is a list context and not a scalar one. The parentheses are significant here,making the fourth of those different than the first. If you're assigning to a list (no matter the number of elements),it's a list context. If you're assigning to an array,it's a list context.

Let's look at other expressions you've seen and the contexts they provide. First,here are some that provide scalar context to something:

    $fred = something;
    $fred[3] = something;
    123 + something
    something + 654
    if (something) { ... }
    while (something) { ... }
    $fred[something] = something;

Here are some that provide a list context:

    @fred = something;
    ($fred,$barney) = something;
    ($fred) = something;
    push @fred,something;
    foreach $fred (something) { ... }
    sort something
    reverse something
    print something

3.7.2. Using Scalar-Producing Expressions in List Context

Going this direction is straightforward: if an expression doesn't normally have a list value,the scalar value is automatically promoted to make a one-element list:

    @fred = 6 * 7; # gets the one-element list (42)
    @barney = "hello" . ' ' . "world";

Well,there's one possible catch:

    @wilma = undef; # OOPS! Gets the one-element list (undef)
      # which is not the same as this:
    @betty = ( );    # A correct way to empty an array

Since undef is a scalar value,assigning undef to an array doesn't clear the array. The better way to do that is to assign an empty list.[*]

[*] Well,in most real-world algorithms,if the variable is declared in the proper scope,you will not need to empty it explicitly. This type of assignment is rare in well-written Perl programs. You'll learn about scoping in the next chapter.

3.7.3. Forcing Scalar Context

On occasion,you may need to force scalar context where Perl is expecting a list. In that case,you can use the fake function scalar. It's not a true function because it just tells Perl to provide a scalar context:

    @rocks = qw( talc quartz jade obsidian );
    print "How many rocks do you have?/n";
    print "I have ",@rocks," rocks!/n";        # WRONG,prints names of rocks
    print "I have ",scalar @rocks," rocks!/n"; # Correct,gives a number

Oddly enough,there's no corresponding function to force list context. It turns out you never need it. Trust us on this,too.

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