Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to read __DATA__ with Config::General in Perl?

I'd like to setup Config::General to read from the __DATA__ section of a script instead of an external file. (I realize that's not normally how it works, but I'd like to see if I can get it going. A specific use case is so I can send a script example to another developer without having to send a separate config file.)

According to the perldoc perldata, $main::DATA should act as a valid filehandle. I think Config::General should then be able to use -ConfigFile => \$FileHandle to read it, but it's not working for me. For example, this script will execute without crashing, but the __DATA__ isn't read in.

#!/usr/bin/perl -w

use strict;
use Config::General;
use YAML::XS;

my $configObj = new Config::General(-ConfigFile => $main::DATA);

my %config_hash = $configObj->getall;

print Dump \%config_hash;

__DATA__

testKey = testValue

I also tried:

my $configObj = new Config::General(-ConfigFile => \$main::DATA);

and

my $configObj = new Config::General(-ConfigFile => *main::DATA);

and a few other variations, but couldn't get anything to work.

Is it possible to use Config::General to read config key/values from __DATA__?

like image 386
Alan W. Smith Avatar asked Dec 03 '22 05:12

Alan W. Smith


2 Answers

-ConfigFile requires a reference to a handle. This works:

my $configObj = Config::General->new(
    -ConfigFile => \*main::DATA
);
like image 126
daxim Avatar answered Jan 07 '23 03:01

daxim


The DATA handle is a glob, not a scalar.

Try *main::DATA instead of $main::DATA.

(and maybe try \*main::DATA. From the Config::General docs it looks like you are supposed to pass a filehandle argument as a reference.)


If the -ConfigGeneral => filehandle argument to the constructor doesn't do what you mean, an alternative is

new Config::General( -String => join ("", <main::DATA>) );
like image 28
mob Avatar answered Jan 07 '23 04:01

mob