On Fri, Mar 1, 2013 at 11:00 AM, Shlomi Fish <shlo...@shlomifish.org> wrote:

> Hi Jim,
>
> On Thu, 28 Feb 2013 11:21:59 -0800
> Jim Gibson <jimsgib...@gmail.com> wrote:
>
> >
> > On Feb 28, 2013, at 10:31 AM, Chris Stinemetz wrote:
> >
> > > I want to put a hash declaration in a separate file from the main
> script.
> > > How do I do this correctly?
> > >
> > > perl.pl ( main script )
> > >
> > > #!/usr/bin/perl
> > > use warnings;
> > > use strict;
> > > use Data::Dumper;
> > >
> > > require "lib.pl";
> > >
> > > print Dumper \%hash;
> > >
> > > lib.pl ( library script )
> > >
> > > #!/usr/bin/perl
> > > use warnings;
> > > use strict;
> > >
> > > my %hash = (
> > >   "Version" => 0,
> > >   "SRT" => 11,
> > >   "SRFC" => 12,
> > >   "CFC" => 21,
> > >   "CFCQ" => 22,
> > >   "ICell" => 29,
> > >   "ISector" => 30,
> > >   "Cell" => 31,
> > >   "Sector" => 32,
> > > );
> > >
> > > 1;
> > >
> > > The error I am getting:
> > >
> > > Global symbol "%hash" requires explicit package name at perl.pl line
> 8.
> > > Execution of perl.pl aborted due to compilation errors.
> >
> > Put the following line in the main script:
> >
> > our %hash;
> >
> > Change the "my %hash = ( ... );" declaration in lib.pl to "our %hash =
> > (...);".
> >
> > In your original versions, %hash was a lexical variable in lib.pl, and
> thus
> > not in scope within perl.pl. Using 'our' instead of 'my' makes %hash a
> > package variable (in package main::), and as such is accessible by both
> > perl.pl and lib.pl, The 'our' declaration also lets you leave off the
> package
> > name when you access the variable.
> >
>
> It is a better idea to put this inside a module and export a subroutine for
> accessing it (or use an object-oriented interface). See:
>
> http://perl-begin.org/topics/modules-and-packages/
>
> Untested code:
>
> <<<<
> ## This is the file MyModule.pm - don't call it that.
> package MyModule;
>
> use parent 'Exporter';
>
> our @EXPORT = (qw(get_ref_to_global_hash));
>
> my %global_hash = (
>         'donald' => 'duck',
>         'mickey' => 'mouse',
>         'goofy' => 'dog',
> );
>
> sub get_ref_to_global_hash
> {
>         return \%global_hash;
> }
>
> # Module should return a true value.
> 1;
> >>>>
>
> Regards,
>
>         Shlomi Fish
>
> --
> -----------------------------------------------------------------
> Shlomi Fish       http://www.shlomifish.org/
> Interview with Ben Collins-Sussman - http://shlom.in/sussman
>
> Sometimes you don’t need to be familiar with a better alternative to know
> that
> something sucks. Take Microsoft Word for example.
>     — Shlomi Fish’s friend.
>
> Please reply to list if it's a mailing list post - http://shlom.in/reply .
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>
> How would I then access the hash in the main script?

Thank you,

Chris

Reply via email to