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?
Asked
Active
Viewed 3.1k times
3

Greg Bacon
- 134,834
- 32
- 188
- 245

Jackie James
- 785
- 8
- 15
- 28
-
2Did you try to find the solution yourself? The Google search "how to write to a file in perl" gives 35.4 mio results – Martin Jun 14 '12 at 10:41
-
2open FILE, ">", "filename.txt" or die $! – Jackie James Jun 14 '12 at 10:43
-
can anyone let me know if u know ? – Jackie James Jun 14 '12 at 10:50
-
@Jackie: from your comment you appear to know the answer. What further help do you need? – Borodin Jun 14 '12 at 10:53
-
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 ? – Jackie James Jun 14 '12 at 11:02
-
@Jackie: yes it does. Then you can print to it using `print FILE $variable, 99, "string"` or similar. Experiment and you will see. – Borodin Jun 14 '12 at 11:31
-
1Regarding your question's title, please write ["perl" or "Perl" but never "PERL"](http://perldoc.perl.org/perlfaq1.html#What's-the-difference-between-%22perl%22-and-%22Perl%22%3f). – pilcrow Jun 14 '12 at 13:02
-
1`$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` variables – plusplus Jun 14 '12 at 13:29
3 Answers
15
#!/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.

szabgab
- 6,202
- 11
- 50
- 64

Jagtesh Chadha
- 2,632
- 2
- 23
- 30
1
Another option: File::Slurp provides convenient read_file
and write_file
functions
write_file('/path/file', @data);
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.

Daniel Böhmer
- 14,463
- 5
- 36
- 46