Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

The main problem is that my declares a lexical variable, meaning it is restricted to its lexical scope. evaled code has its own lexical scope, so the surrounding code can't see the %hash1 declared inside the evaled code. One possible way to fix this issue would be to append some code to the string that you are evaling that returns the values, so for example something like my $hash1ref = eval($code."; return \\%hash1;");

However, eval will execute arbitrary code, and if you use it for untrusted code, it might allow an attacker to inject any code into your system, which is of course a bad thing. One possible way around this is with my module Config::Perl, which will parse data structures like the one you showed. For example:

use warnings; use strict; use Config::Perl; use Data::Dumper; my $parser = Config::Perl->new; my $data = $parser->parse_or_die('file.pl'); my %hash1 = %{ $data->{'%hash1'} }; print Dumper(\%hash1); __END__ $VAR1 = { 'hi' => 2, 'hello' => 1 };

Another issue with your original code is that you need to give eval a string, not a filehandle. A simple way to slurp a file into memory is my $code = do { local $/; <$fh> };. Also, if you really want to use eval, you should check it for errors, in the above example by checking if $hash1ref is defined or not. Update: Also, instead of evaling a file, there's do. But as I said, I wouldn't recommend these methods.


In reply to Re: Reading a hash structure stored in a file by haukex
in thread Reading a hash structure stored in a file by sam1990

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-24 00:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found