Search code examples
perlserializationevaldata-dumper

I serialized my data in Perl with Data::Dumper. Now when I eval it I get "Global symbol "$VAR1" requires explicit package name"


I serialized my data to string in Perl using Data::Dumper. Now in another program I'm trying to deserialize it by using eval and I'm getting:

Global symbol "$VAR1" requires explicit package name

I'm using use warnings; use strict; in my program.

Here is how I'm evaling the code:

my $wiki_categories = eval($db_row->{categories});
die $@ if $@;
/* use $wiki_categories */

How can I disable my program dying because of "$VAR1" not being declared as my?

Should I append "my " before the $db_row->{categories} in the eval? Like this:

my $wiki_categories = eval("my ".$db_row->{categories});

I didn't test this yet, but I think it would work.

Any other ways to do this? Perhaps wrap it in some block, and turn off strict for that block? I haven't ever done it but I've seen it mentioned.

Any help appreciated!


Solution

  • This is normal. By default, when Data::Dumper serializes data, it outputs something like:

    $VAR1 = ...your data...
    

    To use Data::Dumper for serialization, you need to configure it a little. Terse being the most important option to set, it turns off the $VAR thing.

    use Data::Dumper;
    
    my $data = {
        foo => 23,
        bar => [qw(1 2 3)]
    };
    
    my $dumper = Data::Dumper->new([]);
    $dumper->Terse(1);
    
    $dumper->Values([$data]);
    print $dumper->Dump;
    

    Then the result can be evaled straight into a variable.

    my $data = eval $your_dump;
    

    You can do various tricks to shrink the size of Data::Dumper, but on the whole it's fast and space efficient. The major down sides are that it's Perl only and wildly insecure. If anyone can modify your dump file, they own your program.

    There are modules on CPAN which take care of this for you, and a whole lot more, such as Data::Serializer.