Combine eval() with Data::Dumper

| | 评论(0) | 引用通告(0)

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);

分类

引用通告(0)

被引用的日记: Combine eval() with Data::Dumper

TrackBack URL for this entry: http://www.debagua.net/cgi-bin/mt4/mt-tb.cgi/99
如果您想引用这篇日记到您的Blog,
请复制上面的链接,放置到您发表文章时的相应界面中。

发表评论

关于此日记

此日记由mach发表于2007年4月12日 12:03

此Blog上的上一篇日记中国极地研究中心-世界极地年科普展览

此Blog上的下一篇日记标记照片的地理坐标

主索引归档页可以看到最新的日记和所有日记。

Powered by Movable Type 4.0