Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: how to read perl variable from a line read from a file

by Anonymous Monk
on Jan 31, 2013 at 15:17 UTC ( [id://1016336]=note: print w/replies, xml ) Need Help??


in reply to how to read perl variable from a line read from a file

Hopefully a less hackish (safer) solution than what has been offered so far. We use a hash called %vars to contain your variables because it's simply a good idea.

use Data::Dumper; my %vars; # set initial variables $vars{'INST'} = 'C'; open my $fh, "<", 'file' or die $!; while (<$fh>) { chomp; m/^(\w+)=(.*)$/ or next; my ($var, $value) = ($1, $2); $value =~ s/\$([a-z]+)/ $vars{$1} /gie; $vars{$var} = $value; } print Dumper(\%vars);
# source file: VAR1=$INST/dirivebase/program VAR2=$INST/origbase/data # output: $VAR1 = { 'VAR1' => 'C/dirivebase/program', 'INST' => 'C', 'VAR2' => 'C/origbase/data' };

You might want to adjust the regexp to be more lenient towards spacing, though...

Replies are listed 'Best First'.
Re^2: how to read perl variable from a line read from a file
by Bharath666 (Novice) on Jan 31, 2013 at 16:03 UTC

    Thanks!! Its working now....

      It's not perfect. It's missing a close $fh and the substitution regexp probably should be s/\$([a-z]+)/ $vars{$1} || "\$$1" /gie; to give a somewhat sane behaviour for undefined variables (instead of substituting them with the empty string. Which is what *nix shells do, so I guess it's not that bad...)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-19 05:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found