How to create a new file in Perl?
Asked Answered
V

3

5

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?

Vulcanism answered 14/6, 2012 at 10:38 Comment(8)
Did you try to find the solution yourself? The Google search "how to write to a file in perl" gives 35.4 mio resultsSax
open FILE, ">", "filename.txt" or die $!Vulcanism
can anyone let me know if u know ?Vulcanism
@Jackie: from your comment you appear to know the answer. What further help do you need?Coffeng
I want to create a new file & then load data into it. does above command create file by name filename.txt if it doesn't exist ?Vulcanism
@Jackie: yes it does. Then you can print to it using print FILE $variable, 99, "string" or similar. Experiment and you will see.Coffeng
Regarding your question's title, please write "perl" or "Perl" but never "PERL".Kaye
$a and $b aren't good variable names in Perl, since they can conflict or cause confusion with sort()s built in $a and $b variablesFarming
C
16
#!/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.

Carbonari answered 14/6, 2012 at 11:42 Comment(0)
F
2

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

write_file('/path/file', @data);
Farming answered 14/6, 2012 at 13:31 Comment(0)
O
0

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.

Ocd answered 14/6, 2012 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.