双箭头 (=>) 运算符如何在 Perl 中工作? [英] How does double arrow (=>) operator work in Perl?

查看:37
本文介绍了双箭头 (=>) 运算符如何在 Perl 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 => 运算符的哈希使用,像这样

I know about the hash use of the => operator, like this

$ cat array.pl
%ages = ('Martin' => 28,
         'Sharon' => 35,
         'Rikke' => 29,);

print "Rikke is $ages{Rikke} years old
";
$ perl array.pl
Rikke is 29 years old
$

我认为这只是初始化散列的语法,但在对 如何在 Perl 中将变量限定为 const/final ?=> 已被这样使用

and I thought it was just syntax to initialize hashes, but in answers to How can I qualify a variable as const/final in Perl?, => has been used like this

use Readonly;
Readonly my $infilename => "input_56_12.txt";

=> 到底是什么意思?=> 是否有更多的用法?

What exactly does => mean? Are there more ways in which => can be used?

推荐答案

perl 中的 => 运算符与逗号基本相同.唯一的区别是,如果左侧有未引用的单词,则将其视为引用单词.所以你可以写 Martin =>28'Martin', 28 相同.

The => operator in perl is basically the same as comma. The only difference is that if there's an unquoted word on the left, it's treated like a quoted word. So you could have written Martin => 28 which would be the same as 'Martin', 28.

您可以从任何偶数长度列表中生成散列,这就是您在示例中所做的全部工作.

You can make a hash from any even-length list, which is all you're doing in your example.

您的 Readonly 示例通过省略括号来利用 Perl 的子程序参数灵活性.它相当于 Readonly(my $infilename, "input_56_12.txt").Readonly 是 Readonly 模块导出的函数,它接受两个参数:引用和值.如果您想了解 Readonly 的内部结构,则值得另一个问题.

Your Readonly example is taking advantage of Perl's flexibility with subroutine arguments by omitting the parenthesis. It is equivalent to Readonly(my $infilename, "input_56_12.txt"). Readonly is a function exported by the Readonly module which takes two arguments: a reference, and a value. The internals of Readonly are worthy of another question if you want to understand them.

这是一个以意想不到的方式将它用作逗号的示例:

Here's an example of using it as a comma in an unexpected way:

$ perl -e 'print hello => "world
"'
helloworld

这篇关于双箭头 (=>) 运算符如何在 Perl 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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