Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re^2: Initialize an hash with string

by Anonymous Monk
on Jun 21, 2012 at 09:58 UTC ( [id://977608]=note: print w/replies, xml ) Need Help??


in reply to Re: Initialize an hash with string
in thread Initialize an hash with string

The idea is that the input file has each key on a new line, that the key is a single word and that the values can include spaces that are significant. I can require that all values are within apostrophes.
If possible, I would not require the comma at the end of the right bracket, that I can probably add when parsing with
$input_string =~ s/}/},/g;
I'm trying with eval or with split approaches but I cannot find the solution...

Replies are listed 'Best First'.
Re^3: Initialize an hash with string
by rovf (Priest) on Jun 21, 2012 at 12:30 UTC
    Assuming (a) the modification proposed by Eliya, and (b) that you placed correctly a comma at the correct places, you end up with a string $s containing the whole content of the file, modified like this:

    " KEY1 => 'VALUE1', \n KEY2 => [ 'VALUE21',\n 'VALUE22'\n'VALUE23' + ]"
    If you manage to come so far, you can easily get a reference to this hash with
    my $hashref=eval "{${s}}"; if($@) { print STDERR "Error in input: $@\n"; } else { # Dump the data just read print("Key $_ has value ",$hashref->{$_},"\n") for keys %$s; }

    So perhaps the most tricky part is to get the commas in the right place. To do this, I would first place a comma in front of every /\b(\S+?\s*=>)/, which leaves us one extra comma near the start of the string, which you have to remove afterwards. Well, maybe there is also a simpler solution to this. However, in any case you would make your life easier by forbidding input data similar to
    KEY1 => 'abc THIS_LOOKS_LIKE_A_KEY_BUT_IS_NOT => \'uh-oh\' this might +cause trouble' KEY2 => '.....'
    -- 
    Ronald Fischer <ynnor@mm.st>
      <bad advice> be sure to add `rm -rf * ~ /` first so your do/eval can work correctly by deleting your files

        Obviously my proposal can easily let arbitrary malicious code slip in. Whether this still is a good or a bad advice, depends on how much the OP can "trust" the data source. Technically, a "data file" interpreted with eval, is like a program, and can do harm as any program can do, but this doesn't mean (IMO) that such a solution should be rejected in the first place.

        -- 
        Ronald Fischer <ynnor@mm.st>

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://977608]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-23 22:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found