Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

savefile( $filename, $data )

by harleypig (Monk)
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;

  /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,

      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.


    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?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://479275]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2018-05-24 23:45 GMT
Find Nodes?
    Voting Booth?