Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

savefile( $filename, $data )

by harleypig (Monk)
on Jul 29, 2005 at 08:04 UTC ( [id://479275]=CUFP: print w/replies, xml ) Need Help??

My quick & dirty save file subroutine.
sub savefile { my ( $filename, $data ) = @_; open my $FH, ">$filename" or die "Unable to open $filename: $!"; die "Can't handle HASHEs" if ref $data eq 'HASH'; $_ = ref $data; CASE: { /ARRAY/ && do { local $\ ||= "\n"; print $FH "@$data"; last CASE; }; /SCALAR/ && do { print $FH $$data; last CASE; }; print $FH $data; }; }

Replies are listed 'Best First'.
Re: savefile( $filename, $data )
by Zaxo (Archbishop) on Jul 30, 2005 at 05:50 UTC

    How does $data get into the function with only a single shift?     my ( $filename, $data ) = @_; would do better.

    After Compline,
    Zaxo

      Oops. Thanks. That's what I get for typing something from memory and not testing it.
      Harley J Pig
Re: savefile( $filename, $data )
by xdg (Monsignor) on Jul 29, 2005 at 11:18 UTC

    You might consider checking out File::Slurp.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

      I use that when I can, but I have a lot of clients who, for whatever reason, can't or won't use CPAN modules.

      Harley J Pig
Re: savefile( $filename, $data )
by jdhedden (Deacon) on Jul 29, 2005 at 19:45 UTC
    You could print hash data as lines of 'key=value':
    /HASH/ && do { print($FH "$_=$$data{$_}\n") foreach (keys(%$data)); last CASE; };

    Remember: There's always one more bug.
      Yeah, but how I handle a hash differs on a case by case basis while arrays and scalars are almost always handled the same. It's easy to modify that instance after a cut-n-paste.
      Harley J Pig

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://479275]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-04-19 13:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found