http://www.perlmonks.org?node_id=376398

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

Can some one tell me how to output what is in a variable to a file.
I have the variable $mac. Im on a unix machine. How do I get what is in $mac to save to a file on the unix box. Thanks

Replies are listed 'Best First'.
Re: Output to file question
by ysth (Canon) on Jul 21, 2004 at 22:48 UTC
    One way:
    use File::Slurp "write_file"; write_file("filename", $mac) or die "Error writing to file: $!";
    or, more traditionally,
    open my $handle, "> filename" or die "Couldn't open file: $!"; print $handle $mac; close $handle;
    (Ideally, you should check if the print and close fail also; this is commonly overlooked.)
      Thanks
Re: Output to file question
by swkronenfeld (Hermit) on Jul 21, 2004 at 23:35 UTC
    I just want to mention, since it sounds like you are a beginner in Perl, that the method given by ysth will overwrite the contents of your file. If you want to append to a file, you need to open the file as

    open my $handle, ">> filename" or die "Couldn't open file: $!";

    Note the ">>" instead of ">".

    You can print anything else to the file using

    print $handle "Hello, world\n"; print $handle $some_other_var;

    until the close command is executed on $handle.
Am I the only one in love with IO::All?
by Your Mother (Archbishop) on Jul 22, 2004 at 08:32 UTC

    There's also IO::All but you can check comprehension at the door. It's perl voodoo. Here's how to write it once to a file:

    use IO::All; $mac > io('/path/to/file.txt');

    Or append it:

    use IO::All; $mac >> io('/path/to/file.txt');
Re: Output to file question
by beable (Friar) on Jul 22, 2004 at 01:29 UTC
    Here's another way, using the Tie::File module:
    #!/usr/bin/perl use strict; use warnings; use Tie::File; my $mac = "this is the variable to be written to a file"; # tie array to output file tie my @array, 'Tie::File', "outputfile.txt" or die "can't open file: +$!"; # write $mac to file push @array, $mac; # all finished untie @array; __END__