yankel
yankel

Reputation: 145

how to make a hash map (key value pair) from two arrays in perl

I have two arrays of equal length one contains the keys and the other the values.

How do I make them into one hash where I can access it by hash{key} and get the value.

I tried

        my %hash = map { $key[$_], $values[$_] } 0..$#key;

but it kinda saved everything in one long list where every second value is the value as you can see from the debugger.

 DB<104> x %hash
0  'linking_parameter_1'
1  '$$SHIBBOLETH'
2  'service_type'
3  'getFullTxt'
4  'crossref_supported'
5  'Yes'
6  'parser'
7  'Bulk::BULK'
8  'internal_name'
9  'ELSEVIER_SD_EBOOK-COMPLETE_COLLECTION_1995-20065'
10  'object_lookup'
11  'yes'
12  'linking_level'
13  'BOOK'
14  'displayer'
15  'FT::NO_FILL_IN'
16  'parse_param'
17  ''

When I type

x %hash{parser}

it can't evaluate that. maybe I'm just not trying to access it in the right way?

Upvotes: 1

Views: 848

Answers (2)

Borodin
Borodin

Reputation: 126762

Use a hash slice to define it

my %hash;
@hash{@key} = @values;

But the output from the debugger is what you should expect as the hash is expanded into a key/value list before being passed to x. To see the internal structure of composite data you should pass a reference to x

  DB<104> x \%hash
0  HASH(0xe7c88880)
   'linking_parameter_1' => '$$SHIBBOLETH'
   'service_type' => 'getFullTxt'
   'crossref_supported' => 'Yes'
   'parser' => 'Bulk::BULK'
   'internal_name' => 'ELSEVIER_SD_EBOOK-COMPLETE_COLLECTION_1995-20065'
   'object_lookup' => 'yes'
   'linking_level' => 'BOOK'
   'displayer' => 'FT::NO_FILL_IN'
   'parse_param' => ''

Upvotes: 6

simbabque
simbabque

Reputation: 54371

The x command in the Perl debugger takes a list of values. Since a hash in list context is simply a list of values, it cannot see that there are key/value pairs. If you want to see the output as pairs, pass it a reference to your hash.

$ perl -d -e 'my %hash = foo => 123; sleep 1;'
Loading DB routines from perl5db.pl version 1.44
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(-e:1):   my %hash = foo => 123; sleep 1;
  DB<1> s
main::(-e:1):   my %hash = ( foo => 123 ); sleep 1;
  DB<1> x %hash
0  'foo'
1  123
  DB<2> x \%hash   
0  HASH(0x122e9c8)
   'foo' => 123
  DB<3> 

If you want to access an individual hash element, use the correct sigil. To access a scalar value, the sigil is always a $.

  DB<2> x $hash{foo}
0  'foo'
1  123

However, doing %hash{foo} should work too if you don't have use strict and use warnings. Of course you don't want to do that.

Upvotes: 1

Related Questions