Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
Just another Perl shrine
 
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 ( #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...


Comment on Re: how to read perl variable from a line read from a file
Select or Download Code
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
Node Status?
node history
Node Type: note [id://1016336]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-04-24 10:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (565 votes), past polls