Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does double arrow (=>) operator work in 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\n"; $ perl array.pl Rikke is 29 years old $ 

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?

like image 644
Lazer Avatar asked Nov 04 '10 04:11

Lazer


People also ask

What is the difference between -> and => in Perl?

-> will resolve inherited methods making it cleaner and more useful for objects. Foo->Bar(); Foo::Bar('Foo'); This means that -> is generally used in instance methods so that the object is passed its self and constructors so the constructors know which package to bless with.

What does -> indicate in Perl?

The arrow operator ( -> ) is an infix operator that dereferences a variable or a method from an object or a class. The operator has associativity that runs from left to right. This means that the operation is executed from left to right.

How do I dereference a hash reference in Perl?

Dereferencing is the way of accessing the value in the memory pointed by the reference. In order to dereference, we use the prefix $, @, % or & depending on the type of the variable(a reference can point to a array, scalar, or hash etc).

What does F mean in Perl?

f: File is a plain file. - d: File is a directory. - l: File is a symbolic link. - p: File is a named pipe (FIFO), or Filehandle is a pipe. - S: File is a socket. -


1 Answers

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 
like image 81
Ben Jackson Avatar answered Oct 02 '22 08:10

Ben Jackson