[Buffalo-pm] (no subject)

Ben. B. bennymack at gmail.com
Tue Sep 7 07:57:03 PDT 2010


Here's some free code to chew on. The thing to takeaway is that serializing
moderate amounts of data in Perl just require Data::Dumper and the do()
function. There's a lot of other stuff going on as well. E.g. the current
run() method will overwrite the data with what's in the __DATA__ section
every time. It would probably be more useful to have it pull in and build
off what's already in your data file.

# In a file called DataStuff.pm
# perl DataStuff.pm to run
package DataStuff;
use strict;
use warnings;
use Data::Dumper;

__PACKAGE__->run if not caller;

sub run {
    my( $class ) = @_;
    my( $dump ) = do { local $/; <DATA>; };
    my $data1 = eval $dump or die $@;
    $data1->{bum} = 42;
    push @{ $data1->{aref} }, 11;
    $class->save_data( 'foo.pl', $data1 );
    my $data2 = $class->get_data( 'foo.pl' );
    print Dumper( $data2 );
}

sub save_data {
    my( $class, $file_name, $data ) = @_;
    local $Data::Dumper::Terse = 1;
    open my $DATA, '>', $file_name or die "$0 ERROR: write $file_name - $!";
    print $DATA Dumper( $data );
}

sub get_data {
    my( $class, $file_name ) = @_;
    return do $file_name;
}

1;

__DATA__

{
    foo => 1,
    bar => "baz",
    aref => [ 1 .. 10 ],
};


On Tue, Sep 7, 2010 at 10:17 AM, thomas lems <tmlems2000 at yahoo.com> wrote:

> Good morning All,
> I’m new to Perl, and i used  Perl to create a table with five columns and
> 30 rows.  I was able to save the output to a text file, but I’m struggling
> on how to keep the data in the text file cause every time I run the script I
> lose the previous data.
> I believe the issue it’s in the Sub Save Data procedure.
> Here is my Sub SaveData procedure:
> sub SaveData {
>  my ($file_name,$data,$rows,$cols) = @_;
>
>  open(DATA,">$file_name") or die "$0 ERROR: write $file_name - $!";
>  for (my $i=0;$i<$rows;$i++)
>  {
>    for (my $j=0;$j<$cols;$j++)
>    {
>      printf DATA ("<%s> ",$data->{"$i,$j"});
>    }
>    print DATA "\n";
>  }
>  close DATA;
>  exit;
> }
> Please help!
> Thanks
>
>
>
>
> _______________________________________________
> Buffalo Perl Mongers Homepage
> http://buffalo.pm.org
>
> Buffalo-pm mailing list
> Buffalo-pm at pm.org
> http://mail.pm.org/mailman/listinfo/buffalo-pm
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/buffalo-pm/attachments/20100907/5e3f3faa/attachment.html>


More information about the Buffalo-pm mailing list