How to create a new file in Perl?

32.7k Views Asked by At

I've some values stored in the variables $a,$b,$c. Now I've to load these values into new file (create file & load). I'm new to Perl, how can I do it?

3

There are 3 best solutions below

0
Jagtesh Chadha On BEST ANSWER
#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use autodie qw(:all);

my $a = 5;
my $b = 3;
my $c = 10;

#### WRITE ####
{
    open my $fh, '>', 'output.txt';
    print {$fh} $a . "\n";
    print {$fh} $b . "\n";
    print {$fh} $c . "\n";
    close $fh;
}

#### READ ####
{
    open my $fh, '<', 'output.txt';
    my ($a, $b, $c) = <$fh>;
    print $a;
    print $b;
    print $c;
    close $fh;
}

You should read perlopentut and Beginner Perl Maven tutorial: Writing to files.

0
Daniel Böhmer On

Have a look at the methods LoadFile and DumpFile of the YAML module. They are very easy to use as you just need to throw a filename and the actual data against them.

Ask specific questions if don't get along with these.

0
plusplus On

Another option: File::Slurp provides convenient read_file and write_file functions

write_file('/path/file', @data);