Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does {} mean in perl?

Tags:

perl

my $a = {};
my $b = {$a=>''};

I know {} can be used to reference a hash key,but what does {} mean here?

like image 798
new_perl Avatar asked Jun 22 '11 06:06

new_perl


People also ask

What does ~~ mean in Perl?

Just as with the =~ regex match operator, the left side is the "subject" of the match, and the right side is the "pattern" to match against -- whether that be a plain scalar, a regex, an array or hash reference, a code reference, or whatever.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.


2 Answers

{} creates a reference to an empty anonymous hash. Read more here.

Example code:

use Data::Dumper;
my $a = {};
print "a is " . Dumper( $a );
my %b = ();
print "b is " . Dumper( \%b );

Outputs:

a is $VAR1 = {};
b is $VAR1 = {};
like image 194
Flimzy Avatar answered Oct 05 '22 11:10

Flimzy


{}, in this context, is the anonymous hash constructor.

It creates a new hash, assigns the result of the expression inside the curlies to the hash, then returns a reference to that hash.

In other words,

{ EXPR }

is roughly equivalent to

do { my %hash = ( EXPR ); \%hash }

(EXPR can be null, nothing.)

perlref

like image 42
ikegami Avatar answered Oct 05 '22 13:10

ikegami