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

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

by Anonymous Monk
on Jan 31, 2013 at 15:17 UTC ( #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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016336]
[marto]: good morning all
[karlgoethebier]: good morning

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2017-06-29 07:37 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (654 votes). Check out past polls.