Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Output to file question

by dannyp (Novice)
on Jul 21, 2004 at 22:39 UTC ( #376398=perlquestion: print w/replies, xml ) Need Help??

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__

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2022-09-28 01:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer my indexes to start at:




    Results (124 votes). Check out past polls.

    Notices?