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

I would like to configure Config :: General to read from the __DATA__ section of the script instead of the external file. (I understand that this is usually not how it works, but I would like to see if I can do this. In a specific use case, I can send an example script to another developer without sending a separate configuration file.)

According to perldoc perldata , $main::DATA should act as a valid file descriptor. I think Config :: General should use -ConfigFile => \$FileHandle to read, but it does not work for me. For example, this script will run without fail, but __DATA__ not readable.

 #!/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 several other options, but could not get anything to work.

Is it possible to use Config :: General to read the configuration key / values ​​from __DATA__ ?

+4
source share
3 answers

-ConfigFile requires a handle to a handle. It works:

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

the DATA descriptor is a globe, not a scalar.

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

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


If the -ConfigGeneral => filehandle constructor does not do what you mean, an alternative

 new Config::General( -String => join ("", <main::DATA>) ); 
+4
source

This works for me:

 #!/usr/bin/perl use strict; use warnings; use Config::General; use YAML::XS; my $string; { local $/; $string = <main::DATA>; }; my $configObj = new Config::General(-String => $string); my %config_hash = $configObj->getall; use Data::Dumper; warn Dumper(\%config_hash); __DATA__ testKey = testValue 
+1
source

Source: https://habr.com/ru/post/1389339/


All Articles