Search code examples
perlhashglobal-variablessubroutine

Accessing global hash in a subroutine in Perl


I have created a global hash and when I try to access that hash from within a Perl sub routine, it is not able to access it.

I have declared it as:

`%HASH = ();`

and trying to access it in a subroutine as :

$HASH{$key} = $value;

Am I doing something wrong?


Solution

  • Works fine here:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use feature 'say';
    
    our %truth = (); # "global" truth: lexical name
                     # for the package variable %main::truth
    
    sub add_to_truth {
        my ($thing, $value) = @_;
        $truth{$thing} = $value;
    }
    
    add_to_truth(answer => 42);
    say $truth{answer};
    

    Output:

    42
    

    Note that under strictures you have to fully-qualify your "global" variables with their package name (%main::truth in this case) or create a lexically scoped local name for them with our. And programming today without strictures (and warnings) is not a good thing™. In fact, activating them would have told you something useful.