1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
iDev
  • 2,163
  • 10
  • 39
  • 64
  • 1
    Is the hash declared before the sub in the same file? Do you have `use strict` and `use warnings` on? Post some more code – didster Oct 25 '12 at 20:36
  • 1
    Show some relevant code that demonstrates your problem. – TLP Oct 25 '12 at 20:36
  • Thanks guys for your help. I was pushing the hash value in an array using: push (@{$HASH{$key}}, $value) and did not sort my array so couldnot find the value and it seemed to me that it could not access it. My bad, thanks for the help :) – iDev Oct 26 '12 at 02:48
  • 1
    @iDev You are not `push`ing *"in an array"* but in a (anonymous) array reference **INSIDE** your hash. Note that it will be created if it doesn't exist. See the output of [Data::Dumper](http://p3rl.org/Data::Dumper) on your hash to learn more. Learn more about references in the [perlreftut](http://p3rl.org/perlreftut). In almost all situations, `use`ing [strict](http://p3rl.org/strict) and [warnings](http://p3rl.org/warnings) helps to find wrong stuff. [Learn more](http://stackoverflow.com/questions/8023959/why-use-strict-and-warnings) – memowe Oct 26 '12 at 09:20
  • Thanks memowe.. That was informative! :) – iDev Oct 31 '12 at 06:14

1 Answers1

8

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.

memowe
  • 2,656
  • 16
  • 25
  • Is 'our' strictly necessary in this situation? I tried it with 'my' and it worked as well. As I understand it, 'our' is used when you want to share this with the whole package. – tudor -Reinstate Monica- Jun 10 '16 at 00:56