Search code examples
perlserializationperl-io

How to create a new file in Perl?


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?


Solution

  • #!/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.