We help IT Professionals succeed at work.

require and my

Pakman
Pakman asked
on
Medium Priority
187 Views
Last Modified: 2010-03-05
I need a hash with hard-coded values in a 'shared' file. Other files would use the hash in the shared file. However, in the example below %hash from the shared file isn't recognized. What do I need to do to make it work?

********************** a.pl *****************************
use strict;
my (%hash);
require "b.pl";
print %hash;
 
********************** shared.pl **************************
sub gethash {
  %hash = ("number" => 123);
}
1;
Comment
Watch Question

Author

Commented:
Woops! Forgot to add this line after the require statement:

gethash();

Problem still holds.
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
#my (%hash);
use vars qw(%hash);
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
#or
use strict;
my (%hash);
require "b.pl";
%hash=gethash();
print %hash;

Author

Commented:
Okay thanks.

Commented:
In a little bit more modern fashion:

File B.pm (included among many)

package B;
use Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(%hash);

%hash = (
      hashval1 => 1,
      hashval2 => 2,
      hashval3 => 3,
      hashval4 => 4,
     );

1;
## End of file B.pm

File A.pl
#!/usr/local/bin/perl -w

use B qw(%hash);

print "Got third element as $hash{hashval3}\n";
## End of file a.pl

Author

Commented:
Okay okay now how do I get this question to become locked so that I can grade it?

Commented:
Ask ozo to submit his idea as an answer, then grade it when he does so.

Author

Commented:
Ozo submit your idea as an answer.
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
Which one?
You might also consider b2pi's suggestion as a more long term solution.

Author

Commented:
This one:

Comment
      From: ozo
                                                        Date: Monday, August 31 1998 - 10:17AM PDT

      #my (%hash);
      use vars qw(%hash);
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.