eval or do for <DATA>

H

Henry Townsend

I have an irritating little problem - I have a hash (generated by
Data::Dumper) underneath a __DATA__ token and want the script to 'do'
it. E.g. something like this (freehand):

my $hash = do <DATA>;
__DATA__
(Data::Dumper output)

But unfortunately according to "perldoc -f do" it's only defined to
operate on a file name, not a file handle. I really don't want to store
the data in a separate file. Does anyone know a way to drag this stuff
in as if it was in a separate file and I could use "do 'filename'"?

Thanks,
HT
 
U

Uri Guttman

HT> I have an irritating little problem - I have a hash (generated by
HT> Data::Dumper) underneath a __DATA__ token and want the script to 'do'
HT> it. E.g. something like this (freehand):

HT> my $hash = do <DATA>;
HT> __DATA__

HT> But unfortunately according to "perldoc -f do" it's only defined to
HT> operate on a file name, not a file handle. I really don't want to
HT> store the data in a separate file. Does anyone know a way to drag this
HT> stuff in as if it was in a separate file and I could use "do
HT> 'filename'"?

so you put eval in the subject. why did you do that? all do does is
slurp in the file and run eval. so apply the same concept to the DATA
handle. you can slurp it yourself by setting $/ to undef (best in a
local) or use File::Slurp:

use File::Slurp ;

my %hash = eval read_file \*DATA ;

uri
 
U

Uri Guttman

AC> Since "do" is just reading a file into a string and then "eval"-ing the
AC> string, how about this:

AC> my $hash = eval <DATA>;

that will fail as it will only read one line of DATA since eval provides
a scalar context. see my other post for a correct solution.

uri
 
M

Mirco Wahab

Alan said:
Since "do" is just reading a file into a string and then "eval"-ing the
string, how about this:

my $hash = eval <DATA>;

I guess you meant 'eval do' and hesitated writing it ;-)


my $hash = eval do {local $/; <DATA>};


M.
 
H

Henry Townsend

Uri said:
so you put eval in the subject. why did you do that? all do does is
slurp in the file and run eval. so apply the same concept to the DATA
handle. you can slurp it yourself by setting $/ to undef (best in a
local) or use File::Slurp:

Thanks. I did know to try eval but was hung up on the fact that it
forces scalar context; I didn't think to unset $/. Works great now.

HT
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,665
Latest member
salkete

Latest Threads

Top