什么是带有范围运算符的 Perl 上下文? [英] What is the Perl context with range operator?

查看:40
本文介绍了什么是带有范围运算符的 Perl 上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Perl 新手.我想结合范围运算符来理解 Perl 上下文.这是我的代码.

I'm a Perl newbie. I want to understand Perl context in conjunction with range operator. This is my code.

use strict;
use warnings;

my $asc = ( 10 .. 50 );
print "$asc\n";

我有两个疑问.

  1. 如果表达式 ( 10 .. 50 ) 返回一个数组,那么,由于它是一个标量上下文,asc"变量应该被分配数组的长度,即 41.

  1. If the expression ( 10 .. 50 ) returns an array, then, as it's a scalar context, "asc" variable should be assigned the length of the array, that is, 41.

如果表达式 ( 10 ..50 ) 返回一个列表,那么,由于它是一个标量上下文,asc"变量应该被分配到列表中的最后一项,即 50.

If expression ( 10 ..50 ) returns a list, then, as it's a scalar context, "asc" variable should be assigned the last item from the list, that is, 50.

但是,我听到了下面的喊声..

But, I get the following shout ..

Use of uninitialized value in range (or flip) at main.pl line ..

感谢并欢迎任何指南.

推荐答案

您正在使用 标量上下文中的范围运算符 ..,也称为触发器运算符.

You're working with the Range Operator .. in an scalar context, which is otherwise known as the flip-flop operator.

您应该阅读整个文档,但以下摘录与您的情况相关:

You should read the entire documentation, but the following excerpts are relevant to your situation:

在标量上下文中,..";返回一个布尔值.该运算符是双稳态的,就像一个触发器,并模拟 sed、awk 和各种编辑器的行范围(逗号)运算符.

In scalar context, ".." returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors.

...

如果标量.."的任一操作数是一个常量表达式,如果该操作数等于 (==) 当前输入行号($. 变量),则该操作数被视为真.

If either operand of scalar ".." is a constant expression, that operand is considered true if it is equal (==) to the current input line number (the $. variable).

确切"错误消息说明了发生了什么:

The "exact" error message explains what's going on:

Use of uninitialized value $. in range (or flip)

基本上,Perl 将这种用法解释为触发器测试.

Basically, Perl interprets this usage as a flip/flop test.

它正在测试当前行号 $. 是否等于您指定的整数值:

It's testing if the current line number $. is equal to the integer values you specified:

my $asc = ( $. == 10 .. $. == 50 );

但是,由于您尚未读取文件句柄,$. 变量未初始化并引发警告.

However, because you haven't read from a file handle, the $. variable is uninitialized and throws a warning.

可以获得您描述的列表上下文行为,但您需要调整代码以使您的意图更加明确:

It is possible to get the list context behavior that you described, but you'll need to adjust the code to make your intent more explicit:

my $count = () = (10..50);          # Forces a list context
my $last_element = (10..50)[-1];    # Also forces a list context

print "$count\n";
print "$last_element\n";

输出:

41
50

这篇关于什么是带有范围运算符的 Perl 上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆