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?
How to create a new file in Perl?
Asked Answered
#!/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.
Another option: File::Slurp provides convenient read_file
and write_file
functions
write_file('/path/file', @data);
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.
© 2022 - 2024 — McMap. All rights reserved.
print FILE $variable, 99, "string"
or similar. Experiment and you will see. – Coffeng$a
and$b
aren't good variable names in Perl, since they can conflict or cause confusion withsort()
s built in$a
and$b
variables – Farming