简体   繁体   中英

What is the difference between {} and ->{} in Perl?

So if I have some data object and I want to access whats inside the element of that object

Whats the difference between

$Data{isEnabled})

$Data->{isEnabled}

my data is basically like this

for my $characterData (@{$AllCharacters->{'characters'}}) {
$Data{isEnabled})

$Data->{isEnabled}

and i want to access certain elements of my characterData but I'm not sure when to use

$Data{isEnabled})

vs

$Data->{isEnabled}

Like for example why does the first print work but the second fails?

use strict;
use warnings;


my %info = (NAME => "John", HOST => "Local", PORT => 80);

print $info{PORT};
print $info->{PORT};

The first expression accesses a key within a hash:

my %data = (is_enabled => 1);
print $data{is_enabled}), "\n";

In the second expression, data is not a hash, but a *hash reference. It would typically be declared as:

my $data = { is_enabled => 1 };

Since this is a reference, we need to use the dereferencing operator ( -> ) to access the hash content:

print $data->{is_enabled}, "\n";

If you are iterating through an array of hashes, as your code seems to show, then each element is a hash reference. You need to use the second syntax:

my @all_data = ( { is_enabled => 1 }, { is_enabled => 0 } );
for my $data (@all_data) {
    print $data->{is_enabled}, "\n";
}

You can read more about references in the perlref documentation page .

$Data->{isEnabled}

is equivalent to

${ $Data }{isEnabled}

I prefer the "arrow" notation, but it serves my explanation better to compare

$Data{isEnabled}

with

${ $Data }{isEnabled}

In the first case ( $Data{isEnabled} ), we are accessing an element of a hash %Data .

In the second case, we also appear to have a hash lookup, but we have a block ( { $Data } ) where a name would normally be expected. It is indeed a hash lookup, but instead of accessing a named hash, we are accessing a referenced hash. The block (or the expression to the left of the -> ) is expected to return a reference to the hash the program should access.

A reference is a means of referencing a variable through it's location in memory rather than by its name. Consider the following example:

my $ref;
if (condition()) {
   $ref = \%hash1;
} else {
   $ref = \%hash2;
}

say $ref->{id};

This will print $hash1{id} or $hash2{id} based on whether condition() returns a true value or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM