Combine eval() with Data::Dumper
Combine eval with Data::Dumper
eval() is a powerful function in Perl, which is like a virtual machine to execute the input string. People often utilize it as a "dynamic coding" feature.
Data::Dumper is a popular CPAN moudule, which stores the contents of the input reference into a string. Many cameral friends use it to help debugging.
What will happen if I combine those popular functions together? You can store the contents of your hash (not limited to hash, also array, string) to a file, ans also get the contents back easily! Let's start.
#! /usr/bin/perl
use strict;
use Data::Dumper;
# construct a complex hash
my %hash;
@{$hash{'color'}} = ('red', 'green', 'blue', 'yellow', 'cyan', 'magenta', 'coral', 'silver');
%{$hash{'event'}} = ( 'Bach Chamber Music Festival' => '2007-04-13',
'Shanghai International Automobile Exhibition' => '2007-04-24',
'Music of Ono Lisa' => '2007-05-04');
$hash{'updated'} = '2007-04-12';
# save hash to a file 'log'
my $FHANDLE;
unless( open( $FHANDLE, '>log')){
exit -1;
}
print $FHANDLE Dumper(\%hash);
close $FHANDLE;
Now let's check the file 'log'. It should look like this:
$VAR1 = {
'color' => [
'red',
'green',
'blue',
'yellow',
'cyan',
'magarnet',
'coral',
'silver'
],
'updated' => '2007-04-12',
'event' => {
'Bach Chamber Music Festival' => '2007-04-13',
'Music of Ono Lisa' => '2007-05-04',
'Shanghai International Automobile Exhibition' => '2007-04-24'
}
};
# read hash from file
my %hashNew;
unless( open( $FHANDLE, 'log')){
exit -2;
}
my @array = <$FHANDLE>;
close $FHANDLE;
my $VAR1; # must define this while it shows in log file
%hashNew = %{ eval( join( '', @array)) };
if( $@){
print "Syntax error: $@";
exit -3;
}
# show the hash read
print Dumper(\%hashNew);
分类
Software引用通告(0)
被引用的日记: Combine eval() with Data::Dumper。
TrackBack URL for this entry: http://www.debagua.net/cgi-bin/mt4/mt-tb.cgi/99
如果您想引用这篇日记到您的Blog,
请复制上面的链接,放置到您发表文章时的相应界面中。

发表评论