nosbod has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

Graph.pm seems to be a great module. One slight issue though.

I have a script which is called in order to calculate the shortest path between 2 vertices.

Unless i've missed something, each time I run the script I have to create the graph. The graph has ~50,000 edges which means it takes over 10 minutes to build.

Is there some way of writing the graph to disk or storing the graph so that it can be loaded back into memory quicker that recreating the graph from fresh?

TIA

Replies are listed 'Best First'.
Re: storing Graphs created with Graph.pm
by grinder (Bishop) on Mar 20, 2007 at 11:09 UTC

    Looking at the code to Graph, it uses Data::Dumper as for deep copying and dumping. You should therefore be able to dump a Graph object using

    sub write_out { my $graph = shift; my $file = 'graph.dump'; open my $out', '>', $file or die "Cannot open $file for output: $! +\n"; print $out $graph->_dump; close $out or die "Could not close output $file: $!\n"; }

    and then you should be able to read it back in again with:

    sub read_in { my $file = 'graph.dump'; open my $in', '<', $file or die "Cannot open $file for input: $!\n +"; my $Graph; local $/ = undef; # eval { <$in> }; # sets $Graph eval <$in>; # sets $Graph close $in; return $Graph; }

    As an added bonus, the serialised structure is readable (for some definition of readadble...)

    update: string eval, not block eval. Note: you want do this only in a trusted environment. String eval is not something to be used lightly.

    • another intruder with the mooring in the heart of the Perl

Re: storing Graphs created with Graph.pm
by davorg (Chancellor) on Mar 20, 2007 at 09:51 UTC