Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl : Data structure, is this a hash?

Tags:

perl

Assuming I use , say, the following relation

sub _relation {
     +{
        player1   => 0,
        player2  => 1,
        player3    => 0,
      },
      ;
}
  1. How should I print or extract "player1"?
  2. How should I print or extract the value associated with "player2" ?
  3. What kind of data structure is this? Just a hash? No declaration
like image 523
ado Avatar asked Aug 21 '13 04:08

ado


2 Answers

This subroutine returns a hash reference (pointer to a hash.) Curly braces used in this fashion construct an anonymous hash and return a reference to it.

Assuming you call the subroutine something like this:

my $results = _relation();

You would access the elements using the -> dereferencing operator:

$results->{player1}    # 0
$results->{player2}    # 1

If you want to copy the anonymous hash into a named one, you can dereference the entire thing at once with

my %regular_hash = %$results;

See the Perl References Tutorial for more.

like image 139
friedo Avatar answered Oct 10 '22 05:10

friedo


friedo's answer is correct. When trying to understand data structures, it's helpful to use Data::Dumper.

use Data::Dumper;
print Dumper(_relation());

The {}'s in the output show this is an anonymous hash:

$VAR1 = {
          'player3' => 0,
          'player2' => 1,
          'player1' => 0
        };
like image 41
perlrocks Avatar answered Oct 10 '22 03:10

perlrocks