Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
"be consistent"
 
PerlMonks  

savefile( $filename, $data )

by harleypig (Scribe)
on Jul 29, 2005 at 08:04 UTC ( #479275=snippet: print w/ replies, xml ) Need Help??

Description: 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;
};
}
Comment on savefile( $filename, $data )
Download Code
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
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

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2014-04-23 20:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (554 votes), past polls