perlhashpackage

How to access a hash in another file?


Below is the content of P4site.pm:

 our %regVal = (
        'wint' => {
            'Bangalore' => {
                'regSuffix' => 'reg_run',
                'P4PORT' => {
                    'rd' => '9876',
                    'pv' => '1991',
                },
            },
            'Noida' => {  
                 'activeRelease' => {
                    'rd' => {
                             '43.1' => ['rc011', 'nfm'],
                             '98.3' => ['rc008', 'nfm'],
                             '57.3' => ['rc001', 'nfm'],
                     },
                    'pv' => {
                             '43.1' => ['rc011', 'nfm'],
                             '98.3' => ['rc008', 'nfm'],
                             '57.3' => ['rc001', 'nfm'],
                     }
                }

My perl code is:

use strict;
use warnings;
use FindBin qw($Bin);
use lib "$Bin/modules";
use P4site;
use Data::Dumper;

print Dumper(\%{$P4site::regVal});

foreach my $branches (sort keys %{$P4site::{regVal}})
{
    print "$branches is bracnhes\n";
}

Why is sort keys %{$P4site::{regVal}} not giving any output?

Output of the perl code is:

Name "P4site::regVal" used only once: possible typo at allUtilsCopyUserRunMach.pl line 14.
$VAR1 = {};

I was expecting that the keys of regVal hash (mentioned in P4site) would be printed after running this Perl code? How can I print the keys of the regVal hash?


Solution

  • The problem is that you're missing

    package P4site;
    

    in your module. Your code works with this addition.


    While valid, note that %{$P4site::{regVal}} is really weird way of achieving what you want. You're accessing the variable indirectly through a glob of the symbol table. If you don't know what that means, that goes to show how weird it is. You should be using %P4site::regVal instead.


    As for your second question,

    %{ $P4site::regVal{wint}{Noida}{activeRelease} }
    

    and

    $P4site::regVal{wint}{Noida}{activeRelease}->%*
    

    are two ways of getting the hash you want. You can provide these to keys.


    Other improvements: