Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

'do' read file

by PhillipHuang (Beadle)
on Dec 14, 2011 at 08:35 UTC ( [id://943493]=perlquestion: print w/replies, xml ) Need Help??

PhillipHuang has asked for the wisdom of the Perl Monks concerning the following question:

I want to read configuration from a file named '1.spec',and then try to print something. Here's my code:
#!/usr/bin/perl # test.pl use strict; use warnings; my %cfg; unless(do '1.spec'){ warn "can not parse :$@"; warn "can not do: $!"; warn "could not run"; } my @keys = keys %cfg; my @values = values %cfg; while(@keys){ print pop(@keys),'=',pop(@values),"\n"; }
Below is '1.spec', only two lines.
$cfg{name} = 'philip'; $cfg{age} = '21';
I can not get any print when run 'test.pl'. I read perldoc who says 'Do: Uses the value of EXPR as a filename and executes the contents of the file as a Perl script'. If I write 'print "hello"' in 1.spec, it can print as expected, but why it can not set the hash values?

Replies are listed 'Best First'.
Re: 'do' read file
by wfsp (Abbot) on Dec 14, 2011 at 08:47 UTC
Re: 'do' read file
by cdarke (Prior) on Dec 14, 2011 at 08:51 UTC
    do will not alter lexical ('my') variables in the outer scope. To achieve this you have to use a package variable, so delare it using our.

    However, using a file to set your variables can be dangerous, think carefully if you really need to do that. Why not put the keys/values into a file, read it in the normal way, and construct the hash yourself?
      I use 'use vars qw( %cfg );', it can print. and 'our' is also ok. 'vars NOTE: For variables in the current package, the functionality provided by this pragma has been superseded by our declarations, available in Perl v5.6.0 or later'
Re: 'do' read file
by jdporter (Paladin) on Dec 14, 2011 at 15:50 UTC

    You need to be a little more careful about how you handle the return value of do:

    If do cannot read the file, it returns undef and sets $! to the error.

    If do can read the file but cannot compile it, it returns undef and sets an error message in $@ .

    Always check $@ first, as compilation could fail in a way that also sets $! .

    If the file is successfully compiled, do returns the value of the last expression evaluated.

    (Emphasis mine.)

    You're testing for a false return value... but you could get a false value even if do succeeding in reading and executing the file.

    I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.
Re: 'do' read file
by scorpio17 (Canon) on Dec 14, 2011 at 15:10 UTC

    In general, I think it's considered "bad practice" to put executable code into a config file. Try doing something like this instead:

    #!/usr/bin/perl use strict; use Config::Auto; use Data::Dumper; my $config = Config::Auto::parse("1.spec", format => "equal"); print Dumper($config), "\n";

    And change your config file ("1.spec") to something like this:

    NAME = Philip AGE = 21

    When you run this code, you should get this output:

    $VAR1 = { 'NAME' => 'Philip', 'AGE' => '21' };

    In other words, $config is a hash ref pointing to the data read from the config file.

    Config::Auto is very powerful, and can handle much more complicated situations. Read more about it on CPAN.

      In general, I think it's considered "bad practice" to put executable code into a config file.

      So don't think of it as a config file. Think of it as a module for setting some variables.

      (That said, I have nothing against Config::Auto. They should call it Config::Awesome.:-)

      I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.
Re: 'do' read file
by TJPride (Pilgrim) on Dec 14, 2011 at 09:04 UTC
    Depends on if it's a file only he works on, doesn't it.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-04-24 11:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found