How does double arrow (=>) operator work in Perl?

原文链接:https://stackoverflow.com/questions/4093895/how-does-double-arrow-operator-work-in-perl

The use of the => operator can be like this:

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

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

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.

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\n"'
helloworld

From perlop:
The => operator is a synonym for the comma except that it causes its left operand to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores.

This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behaviour, the left operand can be quoted explicitly.

Otherwise, the => operator behaves exactly as the comma operator or list argument separator, according to context.

For example:

use constant FOO => "something";
my %h = ( FOO => 23 );

is equivalent to:

my %h = ("FOO", 23);

It is NOT:

my %h = ("something", 23);

The => operator is helpful in documenting the correspondence between keys and values in hashes, and other paired elements in lists.

%hash = ( $key => $value );
login( $username => $password );

From PBP:

I have found some good information from Perl Best Practices about Fat Commas => and i think it should be nice to mention over here too.

It’s better to reserve the fat comma exclusively for the following things:-

Use it when constructing a hash:

my %h = ( FOO => 23 );

or when passing named arguments to a subroutine ie.,

$text = format_text({FOO => 23, BAR => 30});

or when creating a constant:

 Readonly my $FOO => "23";

For more detail see the Chapter4:Values and Expressions (Fat Commas) section of Perl Best Practices.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值