in reply to Accessing variables in an external hash without eval
G'day victorz22,
[Although you've only been here a while, you've made quite a few posts and should be aware of both "How do I post a question effectively?" and "SSCCE". Even when you can't post real data, you can post dummy data that's representative of what you're working with. Posting the type of thing you have here helps no one.]
You can do what you want ("without eval") by using require.
Instead of repeatedly doing I/O every time you want to access some value from your data, I recommend you read the file and capture the data once; it can then be used as many times as you want (without further I/O).
Furthermore, rather than changing directory and then accessing a file, I'd suggest accessing a path directly. You can use File::Spec to do this.
I dummied up this data for you:
$ cat pm_1190415/external/external_hash %hash = ( scopeX => { modelA => [qw{XA XA XA}], modelB => [qw{XB XB XB}], }, scopeY => { modelA => [qw{YA YA YA}], modelB => [qw{YB YB YB}], }, scopeZ => { modelA => [qw{ZA ZA ZA}], modelB => [qw{ZB ZB ZB}], }, ); 1;
This script shows techniques for achieving all of my recommendations:
#!/usr/bin/env perl -l use strict; use warnings; use File::Spec; my ($dir, $file) = qw{pm_1190415/external external_hash}; my $extern_hash = get_extern_hash($dir, $file); print "@{$extern_hash->{scopeX}{modelB}}"; print "@{$extern_hash->{scopeZ}{modelA}}"; sub get_extern_hash { my $path = File::Spec::->catfile(@_); our %hash; require $path; return \%hash; }
Here's the output:
XB XB XB ZA ZA ZA
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Accessing variables in an external hash without eval
by afoken (Chancellor) on May 17, 2017 at 07:36 UTC |