为什么我不能在Perl中使用钻石算子和数组? [英] Why can't I use the diamond operator with an array in Perl?

查看:124
本文介绍了为什么我不能在Perl中使用钻石算子和数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


代码



  $ cat test1 
hello
i am
lazer

nananana
$ cat 1.pl
use strict;
使用警告;

我的@fh;
打开$ fh [0],'<','test1',或者$!

my @ res1 =< $ fh [0]>; #方法1:为什么这不能按预期工作?
print @ res1。\\\
;

my $ fh2 = $ fh [0];
my @ res2 =< $ fh2>; #方法2:这个工程!
print @ res2。\\\
;




运行




  $ perl 1.pl 
1
5
$

我不确定为什么 Way1 Way2 的确如此。这两种方法不一样吗?这里发生了什么?

解决方案

由于<>运算符的双重性质(即 glob readline ?),规则是表现为readline,方括号内只能有一个空格或简单的标量。所以你必须将数组元素分配给一个简单的标量(如你的例子),或直接使用readline函数。

Code

$ cat test1
hello 
i am 
lazer

nananana
$ cat 1.pl
use strict;
use warnings;

my @fh;
open $fh[0], '<', 'test1', or die $!;

my @res1 = <$fh[0]>;  # Way1: why does this not work as expected?
print @res1."\n"; 

my $fh2 = $fh[0];
my @res2 = <$fh2>;    # Way2: this works!
print @res2."\n";

Run

$ perl 1.pl
1
5
$

I am not sure why Way1 does not work as expected while Way2 does. Aren't those two methods the same? What is happening here?

解决方案

Because of the dual nature of the <> operator (i.e. is it glob or readline?), the rules are that to behave as readline, you can only have a bareword or a simple scalar inside the brackets. So you'll have to either assign the array element to a simple scalar (as in your example), or use the readline function directly.

这篇关于为什么我不能在Perl中使用钻石算子和数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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